Flowchart - How to Solve Coding Problem?
Last updated
Was this helpful?
Last updated
Was this helpful?
Reference -
Given an array of distinct integer values, count the number of pairs of integers that have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3} and the difference k = 2, there are four pairs with difference as 2 i.e. (1, 3), (3, 5), (5, 7), (7, 9).
We need to count distinct pairs (a, b)
in an array such that:
∣a−b∣=k
Given:
An array of distinct integers.
An integer k (positive difference).
We count unordered pairs (e.g., (1,3)
is the same as (3,1)
).
Example:
Valid pairs: (1,3)
, (3,5)
, (5,7)
, (7,9)
Edge cases:
Empty array? → Return 0
Single element? → Return 0
No valid pairs? → Return 0
Negative k? → Not allowed (problem states "difference k")
Already sorted? → Optimize accordingly
A naïve solution checks every pair (i, j)
:
Time Complexity:
O(N²) (Nested loop) – Too slow for large inputs.
We can use a HashSet to check for pairs in O(N) time.
Insert all numbers into a HashSet (O(N) time)
For each number x, check if (x + k) exists in the set
(x, x+k)
is a valid pair
No need to check both (x, x-k)
since it’s already handled by previous elements
Time Complexity: O(N) Space Complexity: O(N)
✔ Base case: [] → 0
✔ Single element: [5] → 0
✔ No valid pairs: [10, 20, 30]
with k = 5 → 0
✔ Large input: Handles efficiently in O(N)
Print all positive integer solutions to the equation a3 + b3 and d are integers between 1 and 1000.
We need to find all positive integer solutions for the equation:
a^3+b^3=c^3+d^3
where a,b,c,d are integers between 1 and 1000.
This means we need to find pairs (a, b) and (c, d) such that their cubes sum to the same value.
A simple approach is to iterate through all possible values of (a, b, c, d) and check if they satisfy the equation.
Correct but VERY slow: O(N⁴) ≈ 10¹² iterations, which is impractical.
Instead of iterating over four nested loops, we can use a HashMap to store sums of cube pairs.
We iterate over (a, b) pairs first, compute a^3 + b^3, and store it in a HashMap.
Then, for each (c, d) pair, we check if the sum exists in the HashMap.
Time Complexity:
O(N²) for precomputing all (a, b) pairs.
O(N²) for checking (c, d) pairs.
Total: O(N²) ≈ 10⁶ iterations, which is feasible.
Precompute cube sums:
We iterate over (a, b) pairs and compute a^3 + b^3.
Store these values in a HashMap, where key = sum of cubes, and value = list of (a, b) pairs.
Find matching pairs efficiently:
If multiple (a, b) pairs have the same cube sum, they form valid (c, d)
pairs.
This eliminates two nested loops, making the solution O(N²).
Time Complexity: O(N²) (Better than O(N⁴)) Space Complexity: O(N²) (Stores sum mappings)