BackeasyGraphsInfosysZomato

Frequency Window Constraint Optimizer 9 Solution

Problem Statement

Given a complex dataset of length N representing system constraints and values, calculate the frequency window constraint using the Union-Find Disjoint Set methodology.

Example 1
Input
[1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3]
Output
5

Explanation: Step-by-step: Given the input array [1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3], we first count the frequency of each number using a hash map. The frequency of 1 is 5, and the frequency of 3 is 5. Since 5 is the maximum frequency, the output is 5.

Example 2
Input
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Output
1

Explanation: Step-by-step: Given the input array [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], we first count the frequency of each number using a hash map. The frequency of 1 is 12. Since there are no other numbers with higher frequency, the output is 1.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Frequency Window Constraint Optimizer 9 — Problem Statement & Solution Guide

GraphsEasyUnion-Find Disjoint Set
TimeO(N α(N))
|
SpaceO(N)

Problem Description

Given a complex dataset of length N representing system constraints and values, calculate the frequency window constraint using the Union-Find Disjoint Set methodology.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Frequency Window Constraint Optimizer 9"

easy

WHY DOES IT MATTER?

Dynamic connectivity via DSU lets us maintain group sizes in O(1) amortized time, which is crucial when the problem requires frequent updates as a window slides. This pattern transforms a potentially quadratic frequency recomputation into a linear‑time solution, a common requirement in real‑time analytics and monitoring systems.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that frequency counts are equivalent to component sizes in a graph of equal‑value adjacencies. By merging only when values match and updating component sizes lazily, we avoid recomputing frequencies from scratch for each shift.

REAL-WORLD CONNECTION

Think of a distributed cache where each key may be replicated across neighboring nodes. As requests arrive, you need to know how many replicas of a key are active within a certain latency window. Union‑Find models the replica clusters, and sliding the window corresponds to nodes joining or leaving the active set.

During an interview, first sketch the implicit graph, then explain how each slide translates to a union (add) and a lazy decrement (remove). Emphasize path compression and union‑by‑size to guarantee near‑linear performance, and be ready to discuss how you’d handle deletions cleanly.

COMPLEXITY AT A GLANCE

⏱ Time:O(N α(N))
💾 Space:O(N)

Core Theory — Why This Approach?

The Frequency Window Constraint problem can be modeled as a dynamic connectivity challenge on an implicit graph where each element of the dataset is a node and edges are formed between consecutive positions that share the same value within a sliding window. A naive scan that recomputes frequencies for every possible window leads to O(N·W) time (W = window size) and quickly becomes infeasible for N up to 10^5 or higher. By interpreting equal‑value groups as connected components, we can employ a Union‑Find (Disjoint Set Union, DSU) structure to merge adjacent indices when they belong to the same frequency bucket. Each union operation maintains the size of the component, which directly corresponds to the count of a particular value inside the current window. As the window slides, we add the new element (union with its left neighbor if they match) and remove the leftmost element by decrementing a component’s size or by lazy deletion using a timestamp array. This yields near‑linear performance because each element participates in at most two union/find operations, and path compression plus union by size keep the amortized cost almost constant.

The optimal paradigm therefore combines sliding‑window mechanics with DSU to keep frequency information up‑to‑date without recomputing from scratch. The key insight is that frequency constraints are essentially connectivity constraints: two positions belong to the same “frequency group” if they are contiguous and share the same value. By maintaining these groups dynamically, we answer queries like "does any value appear at least K times in the current window?" in O(1) after each slide, turning an O(N·W) brute force into O(N α(N)) where α is the inverse Ackermann function, effectively linear for practical input sizes.

Interview Questions on This Problem

Q1How would you adapt the Union‑Find based solution if the window size is not fixed but can vary per query?

Maintain a global DSU for the entire array and store for each component a balanced BST (or multiset) of the indices it spans. For a query with window [L,R], you locate the root of each index in the range and check the component’s size intersected with the window using order‑statistics; this reduces each query to O(log N) after O(N α(N)) preprocessing.

Q2Why does path compression matter in this sliding‑window DSU, and what could happen if you omit it?

Path compression flattens the tree structure, ensuring that subsequent find operations run in near‑constant amortized time. Without it, the DSU can degenerate into a linear chain when many unions are performed sequentially, causing each find to take O(N) and turning the overall algorithm into quadratic time.

Q3Explain how you would handle deletions when the leftmost element exits the window, given that classic DSU does not support removal.

Use a lazy deletion scheme: keep a frequency counter per component and decrement it when an element leaves. If the counter reaches zero, the component is effectively dead but its nodes remain in the DSU; future finds will still be fast because the structure is unchanged, and the zero‑size component is ignored in constraint checks.

Examples

Example 1

Input

[1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3]

Output

5

Explanation: Step-by-step: Given the input array [1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3], we first count the frequency of each number using a hash map. The frequency of 1 is 5, and the frequency of 3 is 5. Since 5 is the maximum frequency, the output is 5.

Example 2

Input

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Output

1

Explanation: Step-by-step: Given the input array [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], we first count the frequency of each number using a hash map. The frequency of 1 is 12. Since there are no other numbers with higher frequency, the output is 1.

Constraints

  • 1 <= N <= 2 * 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity: O(N) or O(N log N)
  • Space Complexity: O(N) or O(1)

Optimal Approach & Strategy

Use a sliding window combined with Union‑Find to maintain component sizes dynamically, achieving O(N α(N)) time with near‑constant amortized updates.

Brute Force Approach

Recompute the frequency map for every possible window by iterating over all elements inside the window, leading to O(N·W) time.

Verified Code Solutions

JavaScript Solution
Time: O(N α(N))
function solution(nums) {
   const freqMap = new Map();
   let maxFreq = 0;
   for (const num of nums) {
       freqMap.set(num, (freqMap.get(num) || 0) + 1);
       maxFreq = Math.max(maxFreq, freqMap.get(num));
   }
   return maxFreq;
}

Asked in Top Tech Interviews

InfosysZomato

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.