Uber | onsite | Interesting Subsquences
Company: Uber
Role: software engineer i, software engineer ii
Interview Stage: Onsite
Location: unknown
Year: unknown
Original Post Content:
You are given an array a of size n and integers k and z. Find the number of subsequences of length k such that absolute difference between any two elements in that subsequence is atleast z i.e |ai-aj| >= z.
Logic:
1. Firstly we will sort the array (order does not matter)
2. first we will store for every index i the maximum index j such that |ai-aj| >= z. and i > j. (we can use stack for O(n)
3. the we will define dp[i][j] where it denotes number of subsequences of length j till i including ith element.
4. now to calculate dp[i][j] = summation(dp[index][j-1]) where 0 <= index <= L. where L is the index that we calculate for every element in step 2.
5. we can basically maintain presum dp[index][j] that can be used in next step to calculate dp[i][j+1] in O(1)
This is the logic you can ask doubts you have I will answer all of them