Count Stable Subsegments Where Adjacent Elements Differ by at Most 1
Company: Citadel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
Overview: Given an integer array, count the contiguous subsegments in which every pair of adjacent elements differs by at most 1. It tests turning a pairwise condition into a linear-time counting argument and keeping counts correct when they exceed 32-bit range.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- The answer is at most 5,000,050,000, which exceeds 2^31-1, so Java returns long and C++ returns long long.
Examples
Input: ([1, 2, 3, 7, 8],)
Expected Output: 9
Explanation: Source example 1: runs of length 3 and 2 give 6 + 3 = 9.
Input: ([5, 5, 5, 5],)
Expected Output: 10
Explanation: Source example 2: all four values are equal, so all 10 slices are stable.
Hints
- One adjacent pair that differs by more than 1 makes every slice containing both of its elements unstable, so such pairs split the array into separate pieces.
- Work out how many stable slices a fully stable block of length k contains, and check it against an all-equal array such as [5, 5, 5, 5], which has 10.
- For a long array the count can exceed 2^31-1, so pick an integer type for it with that in mind.