Consecutive Numbers
Medium
Topics
Each row of matrix is a log entry [id, num]. The ids are distinct but the rows arrive in no particular order.
Order the rows by id ascending. Return every value that occupies three or more adjacent positions in that order, each value once, ascending.
LeetCode poses this as a SQL question over a Logs table. Here the table arrives as a matrix named matrix, which keeps the question identical while making it answerable in the four judge languages.
Example 1
[1]. A value qualifies by occupying three or more adjacent positions in that order, so the input order is not the order the question is about. These rows happen to arrive already in id order, which makes the sort invisible on this input and essential on others.Input: matrix = [[1,1],[2,1],[3,1],[4,2],[5,1],[6,2],[7,2]] Output: [1] Explanation: Ordered by id the values run 1,1,1,2,1,2,2 — the three 1s at the start qualify, while 2 only ever appears twice in a row.
Example 2
Input: matrix = [[3,5],[1,5],[2,5]] Output: [5] Explanation: The rows arrive out of order; sorted by id they are all 5, so 5 qualifies.
Example 3
Input: matrix = [[1,1],[2,2],[3,1]] Output: [] Explanation: No value is adjacent to itself three times, so nothing qualifies.
Constraints
- 1 <= matrix.length <= 10^4
- matrix[i].length == 2
- ids are distinct
- -10^4 <= num <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
The rows arriving unordered is the whole trap. "Three in a row" means three adjacent once the rows are in id order, so walking the input as given answers a different question and happens to be right only when the input is already sorted.
Sort by id first. After that the problem is a plain run-length question: walk the values keeping the current value and how long its run is, and record the value when the run reaches three.
Recording at exactly three rather than at the end of the run is what keeps a long run from being reported repeatedly — a run of five would otherwise be recorded three times. Using a set makes that moot, but the set is also what the "each value once" requirement needs for a value with two separate long runs.
The output order matters here. The values are recorded in the order their runs appear, which is not ascending, so the collected values have to be sorted before returning.
Approach
- Sort the rows by
idascending. - Walk the sorted values tracking the current value and the length of its run.
- When the value changes, reset the run to one. When it repeats, increase the run.
- When a run reaches exactly three, add the value to a set.
- Return the set’s contents sorted ascending.
Walkthrough
matrix = [[1,1],[2,1],[3,1],[4,2],[5,1],[6,2],[7,2]]
sorted by id, the values are
id: 1 2 3 4 5 6 7
num: 1 1 1 2 1 2 2
walking
1 run 1
1 run 2
1 run 3 -> record 1
2 run 1 (value changed)
1 run 1 (value changed)
2 run 1 (value changed)
2 run 2
qualifying values {1}, sorted -> [1]
2 reaches a run of only 2, so it does not qualify.
matrix = [[3,5],[1,5],[2,5]]
as given, the values are 5,5,5 and the answer happens
to come out right -- but only by luck. Sorting by id
gives ids 1,2,3 with values 5,5,5, which is the order
the question is actually about.
a case where it matters:
matrix = [[1,7],[3,7],[2,9],[4,7]]
as given: 7,7,9,7 -> no run of three
by id: 7,9,7,7 -> still no run of three
different sequences, and on other inputs they
disagree about the answer.Complexity
- Time — O(n log n): the sort dominates; the walk is linear.
- Space — O(n): the sorted rows, plus a set of qualifying values.
Common Pitfalls
- Walking the rows as given. Adjacency is defined by
idorder, not input order. - Reporting a value once per position in a long run. Each qualifying value appears once in the answer.
- Requiring exactly three rather than three or more. A run of five still qualifies.
- Returning the values in the order their runs were found rather than ascending.
- Comparing against the previous row’s id to detect a gap. This statement defines adjacency by position after sorting, so gaps in the ids do not break a run.
Full Solution — all languages
class Solution:
def consecutiveNumbers(self, matrix):
# "Three in a row" is about id order, which the input does not supply.
rows = sorted(matrix, key=lambda row: row[0])
qualifying = set()
current = None
run = 0
for row in rows:
num = row[1]
if num == current:
run += 1
else:
current = num
run = 1
if run == 3:
qualifying.add(num)
return sorted(qualifying)import java.util.*;
class Solution {
public java.util.List<Integer> consecutiveNumbers(int[][] matrix) {
int[][] rows = new int[matrix.length][];
for (int i = 0; i < matrix.length; i++) rows[i] = matrix[i].clone();
Arrays.sort(rows, (x, y) -> Integer.compare(x[0], y[0]));
java.util.TreeSet<Integer> qualifying = new java.util.TreeSet<>();
boolean started = false;
int current = 0, run = 0;
for (int[] row : rows) {
int num = row[1];
if (started && num == current) run++;
else {
current = num;
run = 1;
started = true;
}
if (run == 3) qualifying.add(num);
}
return new java.util.ArrayList<>(qualifying);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> consecutiveNumbers(vector<vector<int>>& matrix) {
vector<vector<int>> rows = matrix;
sort(rows.begin(), rows.end(), [](const vector<int>& x, const vector<int>& y) {
return x[0] < y[0];
})
;
set<int> qualifying;
bool started = false;
int current = 0, run = 0;
for (auto& row : rows) {
int num = row[1];
if (started && num == current) run++;
else {
current = num;
run = 1;
started = true;
}
if (run == 3) qualifying.insert(num);
}
return vector<int>(qualifying.begin(), qualifying.end());
}
};/**
* @param {number[][]} matrix
* @return {number[]}
*/ var consecutiveNumbers = function(matrix) {
const rows = matrix.map((r) => r.slice()).sort((x, y) => x[0] - y[0]);
const qualifying = new Set();
let current = null, run = 0;
for (const row of rows) {
const num = row[1];
if (num === current) run++;
else {
current = num;
run = 1;
}
if (run === 3) qualifying.add(num);
}
return [...qualifying].sort((x, y) => x - y);
};