Leetcode 659. Split Array into Consecutive Subsequences
You are given an integer array nums
that is sorted in non-decreasing order.
You need to determine if it is possible to split nums
into one or more subsequences such that:
Return true
if it is possible to split nums
according to the above conditions, otherwise return false
.
10^4
or higher).To solve this problem, we can use a greedy algorithm with the help of two hash maps:
freq
): This map keeps track of the remaining frequency of each integer in nums
.end_map
): This map keeps track of subsequences that end at a particular integer value.Steps to solve the problem:
freq
map with the frequency of each number in nums
.nums
to check if it can be placed in an existing subsequence or if a new subsequence can be started.num-1
can be extended, do so.num
, num+1
, and num+2
.false
.true
.#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isPossible(vector<int>& nums) {
unordered_map<int, int> freq, end_map;
// Fill the frequency map
for (int num : nums) {
freq[num]++;
}
for (int num : nums) {
if (freq[num] == 0) {
continue; // If current number is already used, skip it
}
// Try to add this number to an existing subsequence ending with num - 1
if (end_map[num - 1] > 0) {
end_map[num - 1]--;
end_map[num]++;
}
// If can't extend a previous subsequence, try to start a new one with num, num + 1, num + 2
else if (freq[num + 1] > 0 && freq[num + 2] > 0) {
freq[num + 1]--;
freq[num + 2]--;
end_map[num + 2]++;
}
// If neither, return false
else {
return false;
}
// Decrease the frequency of the current number
freq[num]--;
}
return true;
}
};
The time complexity of this solution is (O(n)), where (n) is the length of the input array nums
. This is because we iterate through the array a constant number of times, performing constant-time operations at each step through the use of hash maps.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?