← Turing Interview Insights

Turing·Software Engineer·Online Assessment (OA)·Intermediate

IntermediatePrefer not to say
Jun 2026Remote

Summary

Got a coding problem from Turing that turned out to be a straight lift from LC 629. Dynamic programming with inverse pair counting, nothing too surprising once you recognize it.

Questions Asked (1)

Q1

Given two integers m and n, count the number of permutations of length m that contain exactly n inverse pairs, where an inverse pair is any pair of indices (x, y) with x < y but the value at x is greater than the value at y. Return the result modulo 10^9 + 7.

Algorithms & Data Structures
Author's notes

Recognized it pretty quickly as a DP problem but still fumbled the transition formula for a bit.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use dynamic programming where dp[i][j] represents the number of permutations of length i with exactly j inverse pairs. The recurrence is dp[i][j] = sum_{k=0}^{min(j, i-1)} dp[i-1][j-k], which can be optimized with prefix sums to O(m*n) time. Return dp[m][n] modulo 10^9+7.

Pro tip: Mention that the maximum number of inverse pairs for length m is m*(m-1)/2, so if n exceeds this, return 0 immediately. Also, using a 1D DP array and updating in-place can save space.

1. Define DP State

Define dp[i][j] as the number of permutations of length i with exactly j inverse pairs. Initialize dp[0][0] = 1 and all other dp[0][j] = 0.

2. Derive Recurrence

When inserting the largest element i into a permutation of length i-1, it can create between 0 and i-1 new inverse pairs. Thus, dp[i][j] = sum_{k=0}^{min(j, i-1)} dp[i-1][j-k].

3. Optimize with Prefix Sums

Compute prefix sums of dp[i-1] to calculate each dp[i][j] in O(1) time, reducing overall time complexity to O(m*n).

4. Handle Edge Cases and Modulo

If n > m*(m-1)/2, return 0. Apply modulo 10^9+7 at each addition to prevent overflow.

5. Return Result

After filling the DP table up to m and n, return dp[m][n] modulo 10^9+7.

Key Points to Mention

  • Dynamic programming state definition and recurrence relation
  • Maximum number of inverse pairs for a given length (m*(m-1)/2)
  • Time and space complexity analysis (O(m*n) time, O(n) space with optimization)
  • Use of prefix sums to optimize the recurrence
  • Modulo arithmetic to handle large numbers
  • Edge cases: n=0, n exceeding maximum possible inverse pairs

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.