Skip to content

659. Split Array into Consecutive Subsequences 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  bool isPossible(vector<int>& nums) {
    unordered_map<int, int> count;
    vector<int> starts;  // the start indices of each subsequence
    vector<int> ends;    // the end indices of each subsequence

    for (const int num : nums)
      ++count[num];

    for (int i = 0; i < nums.size(); ++i) {
      if (i > 0 && nums[i] == nums[i - 1])
        continue;
      const int num = nums[i];
      const int currCount = count[num];
      const int prevCount = count.contains(num - 1) ? count[num - 1] : 0;
      const int nextCount = count.contains(num + 1) ? count[num + 1] : 0;
      for (int j = 0; j < currCount - prevCount; ++j)
        starts.push_back(num);
      for (int j = 0; j < currCount - nextCount; ++j)
        ends.push_back(num);
    }

    for (int i = 0; i < starts.size(); ++i)
      if (ends[i] - starts[i] < 2)
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public boolean isPossible(int[] nums) {
    Map<Integer, Integer> count = new HashMap<>();
    List<Integer> starts = new ArrayList<>(); // the start indices of each subsequence
    List<Integer> ends = new ArrayList<>();   // the end indices of each subsequence

    for (final int num : nums)
      count.merge(num, 1, Integer::sum);

    for (int i = 0; i < nums.length; ++i) {
      if (i > 0 && nums[i] == nums[i - 1])
        continue;
      final int num = nums[i];
      final int currCount = count.get(num);
      final int prevCount = count.getOrDefault(num - 1, 0);
      final int nextCount = count.getOrDefault(num + 1, 0);
      for (int j = 0; j < currCount - prevCount; ++j)
        starts.add(num);
      for (int j = 0; j < currCount - nextCount; ++j)
        ends.add(num);
    }

    for (int i = 0; i < starts.size(); ++i)
      if (ends.get(i) - starts.get(i) < 2)
        return false;

    return true;
  }
}