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;  // start index of subsequence
    vector<int> ends;    // end index of 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.count(num - 1) ? count[num - 1] : 0;
      const int nextCount = count.count(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
30
31
import java.util.List;

class Solution {
  public boolean isPossible(int[] nums) {
    Map<Integer, Integer> count = new HashMap<>();
    List<Integer> starts = new ArrayList<>(); // start index of subsequence
    List<Integer> ends = new ArrayList<>();   // end index of subsequence

    for (final int num : nums)
      count.put(num, count.getOrDefault(num, 0) + 1);

    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.containsKey(num - 1) ? count.get(num - 1) : 0;
      final int nextCount = count.containsKey(num + 1) ? count.get(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;
  }
}