Bird
Raised Fist0
Interview Prepdp-advanced-trees-bitmaskhardAmazonGoogle

Arithmetic Slices II (All Subsequences)

Choose your preparation mode4 modes available
📋
Problem

Imagine you are analyzing stock price trends and want to count all possible arithmetic patterns in the price changes, not just contiguous ones.

Given an integer array nums, return the number of all the arithmetic subsequences of nums. A sequence of numbers is arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) from the array without changing the order of the remaining elements.

1 ≤ nums.length ≤ 1000-2^31 ≤ nums[i] ≤ 2^31 - 1
Edge cases: All elements are the same → maximum arithmetic subsequencesArray with length less than 3 → output 0Array with negative and positive numbers → correct difference handling
</>
IDE
def numberOfArithmeticSlices(nums: list[int]) -> int:public int numberOfArithmeticSlices(int[] nums)int numberOfArithmeticSlices(vector<int>& nums)function numberOfArithmeticSlices(nums)
def numberOfArithmeticSlices(nums):
    # Write your solution here
    pass
class Solution {
    public int numberOfArithmeticSlices(int[] nums) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int numberOfArithmeticSlices(vector<int>& nums) {
    // Write your solution here
    return 0;
}
function numberOfArithmeticSlices(nums) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for all inputs due to missing subsequence counting logic or incorrect base case handling.✅ Add DP logic to count subsequences with difference maps and handle arrays with length >= 3.
Wrong: Incorrect small number (e.g., 1 or 2) for canonical exampleCounting only contiguous arithmetic slices or longest subsequence instead of all subsequences.✅ Use DP with hash maps to count all subsequences sharing the same difference, not just contiguous ones.
Wrong: Wrong large number or overflowed valueInteger overflow in difference calculation causing incorrect map keys or counts.✅ Use 64-bit integers or long type for difference calculations and map keys.
Wrong: Timeout or no output on large inputUsing brute force enumeration instead of O(n^2) DP approach.✅ Implement DP with hash maps to achieve O(n^2) time complexity.
✓
Test Cases
t1_01basic
Input{"nums":[2,4,6,8,10]}
Expected7

The arithmetic subsequences are: [2,4,6], [4,6,8], [6,8,10], [2,4,6,8], [4,6,8,10], [2,4,6,8,10], and [2,4,10].

t1_02basic
Input{"nums":[7,7,7,7]}
Expected5

All subsequences of length >=3 with difference 0: [7,7,7] (3 times), [7,7,7,7] (1 time), total 5 arithmetic subsequences.

t2_01edge
Input{"nums":[]}
Expected0

Empty array has no subsequences of length >= 3.

t2_02edge
Input{"nums":[5]}
Expected0

Single element array cannot form arithmetic subsequences of length >= 3.

t2_03edge
Input{"nums":[1,3,5]}
Expected1

Only one arithmetic subsequence of length 3: [1,3,5].

t3_01corner
Input{"nums":[1,2,4,7,11]}
Expected3

Arithmetic subsequences: [1,4,7], [4,7,11], and [1,4,7,11] with differences 3.

t3_02corner
Input{"nums":[1,3,5,7,9,11]}
Expected16

All arithmetic subsequences with difference 2, including all subsequences of length >= 3.

t3_03corner
Input{"nums":[1,1000000000,2000000000]}
Expected1

One arithmetic subsequence: [1, 1000000000, 2000000000] with large differences.

t4_01performance
Input{"nums":[1000,999,998,997,996,995,994,993,992,991,990,989,988,987,986,985,984,983,982,981,980,979,978,977,976,975,974,973,972,971,970,969,968,967,966,965,964,963,962,961,960,959,958,957,956,955,954,953,952,951,950,949,948,947,946,945,944,943,942,941,940,939,938,937,936,935,934,933,932,931,930,929,928,927,926,925,924,923,922,921,920,919,918,917,916,915,914,913,912,911,910,909,908,907,906,905,904,903,902,901]}
⏱ Performance - must finish in 2000ms

Input size n=100 with descending sequence to test O(n^2) DP performance within 2 seconds.

Practice

(1/5)
1. Given the following code snippet and input person_caps = [[5, 100], [1, 5, 100], [1, 2]], what is the final returned value of count_ways_space_optimized(person_caps)?
easy
A. 3
B. 6
C. 4
D. 5

Solution

  1. Step 1: Trace dp array updates for each cap

    Initially dp[0]=1. Caps 1,2,5,100 appear. Assigning caps to persons updates dp masks. For example, cap 5 can assign to person 0 or 1, cap 1 to person 1 or 2, etc.
  2. Step 2: Calculate final dp[(1<<3)-1] = dp[7]

    After processing all caps, dp[7] counts all unique assignments. Manual tracing shows dp[7] = 4.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Manual bitmask DP tracing confirms 4 unique assignments [OK]
Hint: Trace dp updates backward to count unique assignments [OK]
Common Mistakes:
  • Off-by-one in mask indexing
  • Forgetting to iterate masks backward
2. You are given a binary tree and need to find the length of the longest path between any two nodes in the tree. This path may or may not pass through the root. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. A brute force approach that computes the height of every subtree multiple times and checks all paths.
B. A bottom-up depth-first search (DFS) that computes heights and updates the diameter in a single traversal.
C. A greedy approach that always chooses the longest child path at each node without recursion.
D. A dynamic programming approach on arrays that stores intermediate results for subproblems unrelated to tree structure.

Solution

  1. Step 1: Understand the problem requires longest path between any two nodes, not necessarily through root

    The problem is to find the diameter, which is the longest path between any two nodes in the tree, possibly passing through any node.
  2. Step 2: Identify the approach that computes height and diameter simultaneously in one DFS traversal

    The bottom-up DFS approach computes the height of subtrees and updates the diameter during the same recursion, ensuring O(n) time complexity.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Bottom-up DFS avoids repeated height computations and covers all paths [OK]
Hint: Diameter requires single DFS updating max path sum [OK]
Common Mistakes:
  • Assuming diameter passes only through root
  • Using greedy without recursion
  • Repeated height computations causing inefficiency
3. You are given a list of pairs of integers where each pair represents a start and end point. You want to find the longest sequence of pairs such that for every consecutive pair (a, b) and (c, d) in the sequence, b < c. Which algorithmic approach guarantees finding the optimal longest sequence efficiently?
easy
A. Dynamic Programming with sorting pairs by their start values and checking all subsequent pairs
B. Greedy algorithm sorting pairs by their end values and selecting pairs that start after the last selected pair ends
C. Pure brute force recursion checking all possible sequences without sorting
D. Sorting pairs by their start values and greedily selecting pairs with the earliest start

Solution

  1. Step 1: Understand the problem constraints

    The problem requires selecting pairs so that each pair starts after the previous one ends, maximizing the chain length.
  2. Step 2: Identify the optimal approach

    Sorting pairs by their end values allows a greedy selection of the earliest finishing pairs, ensuring maximum room for subsequent pairs.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Greedy by end time is a classic interval scheduling approach [OK]
Hint: Sort by end time for optimal chain [OK]
Common Mistakes:
  • Sorting by start time and applying greedy fails on some inputs
  • Using brute force recursion without pruning is inefficient
  • Assuming DP must sort by start time
4. What is the time complexity of the optimized LIS algorithm using binary search on an input array of length n?
medium
A. O(n log n)
B. O(n)
C. O(n²)
D. O(log n)

Solution

  1. Step 1: Identify outer loop complexity

    The algorithm iterates over all n elements once, so at least O(n).
  2. Step 2: Identify inner operation complexity

    For each element, binary search on tails array takes O(log n) time.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    n iterations x log n binary search -> O(n log n) [OK]
Hint: Binary search inside loop gives n log n [OK]
Common Mistakes:
  • Assuming O(n²) because of nested loops
  • Ignoring binary search complexity
  • Confusing with brute force exponential
5. Suppose the problem is modified so that caps can be assigned to multiple people (i.e., caps are no longer unique). Which of the following algorithmic changes correctly adapts the solution to count the number of ways to assign caps without uniqueness constraints?
hard
A. Remove bitmask tracking and use simple multiplication of counts per person
B. Keep bitmask DP but allow assigning the same cap multiple times by not checking mask bits
C. Use a DP over persons only, multiplying the number of caps each person can wear
D. Use a nested loop over persons and caps without bitmask, summing ways for each person independently

Solution

  1. Step 1: Understand the uniqueness constraint removal

    Without uniqueness, caps can be reused freely, so no need to track assigned caps with bitmasks.
  2. Step 2: Simplify counting approach

    Counting ways reduces to multiplying the number of caps each person can wear, as assignments are independent.
  3. Step 3: Why other options fail

    Bitmask DP is unnecessary and incorrect if caps can be reused; summing independently without multiplication misses combinations.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Removing bitmask and multiplying counts per person matches problem relaxation [OK]
Hint: No uniqueness -> no bitmask needed, multiply counts [OK]
Common Mistakes:
  • Trying to keep bitmask DP unnecessarily
  • Summing instead of multiplying counts
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard