BackmediumGreedyGoogleAmazon

Sensor Checkpoint Aligner 19 Solution

Problem Statement

You are tasked with optimizing the synchronization of a distributed sensor network. The network consists of N sensor nodes, each reporting a unique integer metric value. Two sensors are considered 'aligned' if their metric values differ by at most K. Your goal is to partition the sensors into the maximum number of disjoint groups such that within each group, every pair of sensors is aligned. This is equivalent to finding the maximum number of connected components in a graph where an edge exists between two nodes if their values are within the threshold K.

Given an array metrics of length N and an integer threshold, determine the minimum number of groups required to cover all sensors such that for any two sensors in the same group, the absolute difference between their metrics is at most threshold. Note that this is a greedy problem solvable by sorting and using a Union-Find or sliding window approach to count connected components based on proximity.

Input: An array metrics of integers representing sensor readings and an integer threshold. Output: An integer representing the minimum number of groups (connected components) needed.

Example 1
Input
metrics = [1, 2, 3, 10, 11, 12], threshold = 2
Output
2

Explanation: Sort the metrics: [1, 2, 3, 10, 11, 12]. 1. Start with 1. 2 is within 2 of 1 (diff=1). 3 is within 2 of 1 (diff=2). So {1, 2, 3} form one group. 2. Next is 10. 10 is not within 2 of 3 (diff=7). Start a new group. 3. 11 is within 2 of 10 (diff=1). 12 is within 2 of 10 (diff=2). So {10, 11, 12} form the second group. Total groups = 2.

Example 2
Input
metrics = [5, 10, 15, 20], threshold = 4
Output
4

Explanation: Sort the metrics: [5, 10, 15, 20]. 1. Start with 5. 10 is not within 4 of 5 (diff=5). New group. 2. Start with 10. 15 is not within 4 of 10 (diff=5). New group. 3. Start with 15. 20 is not within 4 of 15 (diff=5). New group. 4. Start with 20. End of list. Each element forms its own group. Total groups = 4.

Example 3
Input
metrics = [1, 1, 1, 1], threshold = 0
Output
1

Explanation: Sort the metrics: [1, 1, 1, 1]. 1. Start with 1. All other 1s are within 0 of 1 (diff=0). They all belong to the same group. Total groups = 1.

Example 4
Input
metrics = [10, 20, 30, 40, 50], threshold = 15
Output
3

Explanation: Sort the metrics: [10, 20, 30, 40, 50]. 1. Start with 10. 20 is within 15 of 10 (diff=10). 30 is within 15 of 10 (diff=20? No, 30-10=20 > 15). Wait, the condition is that *every pair* in the group must be within K. This implies the group must be a clique in the interval graph. For sorted arrays, a valid group is a contiguous subarray where max - min <= K. Let's re-evaluate: Group 1: Start at 10. Can include 20 (20-10=10<=15). Can include 30? 30-10=20>15. So Group 1 is {10, 20}. Group 2: Start at 30. Can include 40 (40-30=10<=15). Can include 50? 50-30=20>15. So Group 2 is {30, 40}. Group 3: Start at 50. {50}. Total groups = 3.

Constraints

  • 1 <= metrics.length <= 10^5
  • 1 <= metrics[i] <= 10^9
  • 0 <= threshold <= 10^9
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

Sensor Checkpoint Aligner 19 — Problem Statement & Solution Guide

GreedyMediumBFS / Union Find
TimeO(N log N)
|
SpaceO(1) additional

Problem Description

You are tasked with optimizing the synchronization of a distributed sensor network. The network consists of N sensor nodes, each reporting a unique integer metric value. Two sensors are considered 'aligned' if their metric values differ by at most K. Your goal is to partition the sensors into the maximum number of disjoint groups such that within each group, every pair of sensors is aligned. This is equivalent to finding the maximum number of connected components in a graph where an edge exists between two nodes if their values are within the threshold K.

Given an array metrics of length N and an integer threshold, determine the minimum number of groups required to cover all sensors such that for any two sensors in the same group, the absolute difference between their metrics is at most threshold. Note that this is a greedy problem solvable by sorting and using a Union-Find or sliding window approach to count connected components based on proximity.

Input: An array metrics of integers representing sensor readings and an integer threshold.

Output: An integer representing the minimum number of groups (connected components) needed.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Sensor Checkpoint Aligner 19"

medium

WHY DOES IT MATTER?

Greedy interval partitioning turns an exponential grouping problem into a linear scan.

OPTIMIZATION CHALLENGE

The key is reducing the combinatorial search to a single pass after sorting.

REAL-WORLD CONNECTION

It mirrors batch processing where jobs are grouped by deadline windows to maximize throughput.

Always verify the greedy choice property—once a group is closed, no later element can be placed earlier without violating the K‑range.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log N)
💾 Space:O(1) additional

Core Theory — Why This Approach?

The problem reduces to covering a sorted list of distinct integers with the smallest possible intervals of length K, but we are asked for the maximum number of groups, which is achieved by making each interval as tight as possible. By sorting the metrics, we can greedily start a new group at the first unassigned sensor and keep adding subsequent sensors while the difference between the current sensor and the group’s first sensor does not exceed K; once this condition fails, we close the group and start a new one. Naïve approaches such as trying all subsets or using dynamic programming explode combinatorially (O(2^N) or O(N^2) states) and cannot handle N up to 10^5. The greedy paradigm leverages the monotonic property of sorted values, guaranteeing optimality because any postponement of a group boundary would only increase its span and potentially reduce the total count of groups.

Interview Questions on This Problem

Q1Why does sorting the sensor values enable a greedy solution for maximizing the number of groups?

Sorting imposes a total order, allowing us to consider intervals sequentially; the earliest possible group closure leaves the most elements for future groups, which is optimal.

Q2What is the time complexity of the optimal algorithm and which step dominates it?

O(N log N) due to the initial sort; the linear scan to form groups is O(N) and does not affect the overall bound.

Q3How would you modify the algorithm if groups were required to have at most M sensors instead of a K‑range constraint?

After sorting, simply start a new group after M elements have been added, ignoring the value differences; this also runs in O(N log N).

Examples

Example 1

Input

metrics = [1, 2, 3, 10, 11, 12], threshold = 2

Output

2

Explanation: Sort the metrics: [1, 2, 3, 10, 11, 12]. 1. Start with 1. 2 is within 2 of 1 (diff=1). 3 is within 2 of 1 (diff=2). So {1, 2, 3} form one group. 2. Next is 10. 10 is not within 2 of 3 (diff=7). Start a new group. 3. 11 is within 2 of 10 (diff=1). 12 is within 2 of 10 (diff=2). So {10, 11, 12} form the second group. Total groups = 2.

Example 2

Input

metrics = [5, 10, 15, 20], threshold = 4

Output

4

Explanation: Sort the metrics: [5, 10, 15, 20]. 1. Start with 5. 10 is not within 4 of 5 (diff=5). New group. 2. Start with 10. 15 is not within 4 of 10 (diff=5). New group. 3. Start with 15. 20 is not within 4 of 15 (diff=5). New group. 4. Start with 20. End of list. Each element forms its own group. Total groups = 4.

Example 3

Input

metrics = [1, 1, 1, 1], threshold = 0

Output

1

Explanation: Sort the metrics: [1, 1, 1, 1]. 1. Start with 1. All other 1s are within 0 of 1 (diff=0). They all belong to the same group. Total groups = 1.

Example 4

Input

metrics = [10, 20, 30, 40, 50], threshold = 15

Output

3

Explanation: Sort the metrics: [10, 20, 30, 40, 50]. 1. Start with 10. 20 is within 15 of 10 (diff=10). 30 is within 15 of 10 (diff=20? No, 30-10=20 > 15). Wait, the condition is that *every pair* in the group must be within K. This implies the group must be a clique in the interval graph. For sorted arrays, a valid group is a contiguous subarray where max - min <= K. Let's re-evaluate: Group 1: Start at 10. Can include 20 (20-10=10<=15). Can include 30? 30-10=20>15. So Group 1 is {10, 20}. Group 2: Start at 30. Can include 40 (40-30=10<=15). Can include 50? 50-30=20>15. So Group 2 is {30, 40}. Group 3: Start at 50. {50}. Total groups = 3.

Constraints

  • 1 <= metrics.length <= 10^5
  • 1 <= metrics[i] <= 10^9
  • 0 <= threshold <= 10^9

Optimal Approach & Strategy

Sort the array and greedily form groups by tracking the first element of the current group; start a new group when the difference exceeds K.

Brute Force Approach

Enumerate every possible partition and check the K‑range condition, which is exponential and infeasible for large N.

Verified Code Solutions

JavaScript Solution
Time: O(N log N)
function solution(nums) {
   let median = nums.sort((a, b) => a - b)[Math.floor(nums.length / 2)];
   let sum = 0;
   for (let i = 0; i < nums.length; i++) {
       if (nums[i] > median) {
           sum += nums[i];
           if (sum >= 5 * median) break;
       }
   }
   return sum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

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.