LeetCode #3832 — HARD

Find Users with Persistent Behavior Patterns

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

Table: activity

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| action_date  | date    |
| action       | varchar |
+--------------+---------+
(user_id, action_date, action) is the primary key (unique value) for this table.
Each row represents a user performing a specific action on a given date.

Write a solution to identify behaviorally stable users based on the following definition:

  • A user is considered behaviorally stable if there exists a sequence of at least 5 consecutive days such that:
    • The user performed exactly one action per day during that period.
    • The action is the same on all those consecutive days.
  • If a user has multiple qualifying sequences, only consider the sequence with the maximum length.

Return the result table ordered by streak_length in descending order, then by user_id in ascending order.

The result format is in the following example.

Example:

Input:

activity table:

+---------+-------------+--------+
| user_id | action_date | action |
+---------+-------------+--------+
| 1       | 2024-01-01  | login  |
| 1       | 2024-01-02  | login  |
| 1       | 2024-01-03  | login  |
| 1       | 2024-01-04  | login  |
| 1       | 2024-01-05  | login  |
| 1       | 2024-01-06  | logout |
| 2       | 2024-01-01  | click  |
| 2       | 2024-01-02  | click  |
| 2       | 2024-01-03  | click  |
| 2       | 2024-01-04  | click  |
| 3       | 2024-01-01  | view   |
| 3       | 2024-01-02  | view   |
| 3       | 2024-01-03  | view   |
| 3       | 2024-01-04  | view   |
| 3       | 2024-01-05  | view   |
| 3       | 2024-01-06  | view   |
| 3       | 2024-01-07  | view   |
+---------+-------------+--------+

Output:

+---------+--------+---------------+------------+------------+
| user_id | action | streak_length | start_date | end_date   |
+---------+--------+---------------+------------+------------+
| 3       | view   | 7             | 2024-01-01 | 2024-01-07 |
| 1       | login  | 5             | 2024-01-01 | 2024-01-05 |
+---------+--------+---------------+------------+------------+

Explanation:

  • User 1:
    • Performed login from 2024-01-01 to 2024-01-05 on consecutive days
    • Each day has exactly one action, and the action is the same
    • Streak length = 5 (meets minimum requirement)
    • The action changes on 2024-01-06, ending the streak
  • User 2:
    • Performed click for only 4 consecutive days
    • Does not meet the minimum streak length of 5
    • Excluded from the result
  • User 3:
    • Performed view for 7 consecutive days
    • This is the longest valid sequence for this user
    • Included in the result

The Results table is ordered by streak_length in descending order, then by user_id in ascending order

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: Table: activity +--------------+---------+ | Column Name | Type | +--------------+---------+ | user_id | int | | action_date | date | | action | varchar | +--------------+---------+ (user_id, action_date, action) is the primary key (unique value) for this table. Each row represents a user performing a specific action on a given date. Write a solution to identify behaviorally stable users based on the following definition: A user is considered behaviorally stable if there exists a sequence of at least 5 consecutive days such that: The user performed exactly one action per day during that period. The action is the same on all those consecutive days. If a user has multiple qualifying sequences, only consider the sequence with the maximum length. Return the result table ordered by streak_length in descending order, then by user_id in ascending order. The result format is in the following

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: General problem-solving

Example 1

{"headers":{"activity":["user_id","action_date","action"]},"rows":{"activity":[[1,"2024-01-01","login"],[1,"2024-01-02","login"],[1,"2024-01-03","login"],[1,"2024-01-04","login"],[1,"2024-01-05","login"],[1,"2024-01-06","logout"],[2,"2024-01-01","click"],[2,"2024-01-02","click"],[2,"2024-01-03","click"],[2,"2024-01-04","click"],[3,"2024-01-01","view"],[3,"2024-01-02","view"],[3,"2024-01-03","view"],[3,"2024-01-04","view"],[3,"2024-01-05","view"],[3,"2024-01-06","view"],[3,"2024-01-07","view"]]}}
Step 02

Core Insight

What unlocks the optimal approach

  • No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3832: Find Users with Persistent Behavior Patterns
// Auto-generated Java example from py.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (py):
// # Accepted solution for LeetCode #3832: Find Users with Persistent Behavior Patterns
// import pandas as pd
// 
// 
// def find_behaviorally_stable_users(activity: pd.DataFrame) -> pd.DataFrame:
//     activity['action_date'] = pd.to_datetime(activity['action_date'])
// 
//     # Filter users with only a single action per day
//     df = activity.assign(
//         cnt=activity.groupby(['user_id', 'action_date'])['action'].transform('count')
//     )
//     df = df[df['cnt'] == 1].sort_values(['user_id', 'action', 'action_date'])
// 
//     # Identify consecutive intervals
//     df['rn'] = df.groupby(['user_id', 'action'])['action_date'].rank(method='first')
//     df['grp'] = df['action_date'] - pd.to_timedelta(df['rn'], unit='D')
// 
//     # Aggregate streaks
//     streaks = (
//         df.groupby(['user_id', 'action', 'grp'])
//         .agg(
//             streak_length=('action_date', 'count'),
//             start_date=('action_date', 'min'),
//             end_date=('action_date', 'max'),
//         )
//         .reset_index()
//     )
// 
//     # Filter and get the longest streak for each user
//     res = streaks[streaks['streak_length'] >= 5].sort_values(
//         ['streak_length', 'user_id'], ascending=[False, True]
//     )
// 
//     return res.groupby('user_id').head(1)[
//         ['user_id', 'action', 'streak_length', 'start_date', 'end_date']
//     ]
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.

OPTIMIZED
O(n) time
O(1) space

Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.

Shortcut: If you are using nested loops on an array, there is almost always an O(n) solution. Look for the right auxiliary state.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.