← J.P. Morgan Interview Insights

J.P. Morgan·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Jun 2026

Summary

Coding round at J.P. Morgan for a software engineer role. Pretty standard algorithmic problem, nothing that'll make you lose sleep, but the in-place constraint is the part that trips people up if they're not careful.

Questions Asked (1)

Q1

Given an integer array, rearrange it in place so all zeros move to the end while preserving the relative order of non-zero elements. No extra arrays allowed, and aim for O(n) time.

Algorithms & Data Structures
Author's notes

Two-pointer approach is the move here.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use a two-pointer technique: one pointer to track the position for the next non-zero element, and another to scan the array. When a non-zero is found, swap it with the element at the first pointer and increment the first pointer. This preserves order and moves zeros to the end in O(n) time with O(1) space.

Pro tip: Mention that this is a stable partition problem and that the two-pointer approach is optimal; also note that swapping is not strictly necessary if you overwrite and fill zeros later, but swapping is simpler and still in-place.

1. Clarify requirements and constraints

Confirm that the array must be modified in place, relative order of non-zero elements must be preserved, and no extra arrays are allowed. Ask about edge cases like empty array or all zeros.

2. Choose the two-pointer strategy

Explain that you'll maintain a pointer (e.g., 'insertPos') for the next non-zero element's position, and iterate through the array with another pointer. This ensures O(n) time and O(1) space.

3. Walk through the algorithm

Describe the loop: for each element, if it's non-zero, swap it with the element at insertPos and increment insertPos. If it's zero, just continue. This moves zeros to the end while keeping non-zeros in order.

4. Analyze complexity and edge cases

State that time complexity is O(n) because each element is visited once, and space is O(1). Discuss edge cases: empty array, all zeros, no zeros, and single element.

5. Test with an example

Trace through a small example like [0,1,0,3,12] to show the swaps and final array [1,3,12,0,0]. This demonstrates correctness and helps the interviewer follow your logic.

Key Points to Mention

  • Two-pointer technique for in-place rearrangement
  • Stable partition: preserving relative order of non-zero elements
  • Time complexity O(n) and space complexity O(1)
  • Edge cases: empty array, all zeros, no zeros
  • Alternative approach: overwrite non-zeros and fill zeros at the end (but swapping is simpler)
  • Avoid using extra arrays or built-in sort functions

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