← JP Morgan Interview Insights

JP Morgan·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
May 2026

Summary

Got a coding question at JP Morgan for a software engineer role, pretty standard greedy string construction problem. Nothing too wild but it required you to actually think through the approach carefully.

Questions Asked (1)

Q1

Given a string and an integer repeatLimit, construct the lexicographically largest string such that no character appears more than repeatLimit times consecutively. You don't have to use all characters.

Algorithms & Data Structures
Author's notes

Knew immediately it was a greedy problem but fumbled the implementation for a bit.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use a greedy strategy with a max-heap to always pick the largest available character, while tracking consecutive counts to enforce the repeatLimit. When the limit is reached, temporarily place the next largest character to break the sequence, then restore the previous character if possible.

Pro tip: Emphasize that you don't need to use all characters, so you can stop when no valid placement exists. Also, mention that this greedy approach is optimal because picking the largest possible character at each step maximizes the lexicographical order.

1. Count frequencies

Compute the frequency of each character in the input string and store them in a frequency map or array.

2. Initialize max-heap

Insert all characters with non-zero frequency into a max-heap (priority queue) ordered by character value.

3. Greedy construction

While the heap is not empty, pop the largest character. If it has been used repeatLimit times consecutively, pop the next largest character, append it, and push the first character back if it still has remaining count.

4. Track consecutive usage

Maintain a variable for the last character used and its consecutive count to enforce the repeatLimit constraint.

5. Terminate and return

Stop when the heap is empty or no valid character can be placed (i.e., only one character remains and its consecutive count equals repeatLimit). Return the constructed string.

Key Points to Mention

  • Greedy choice: always pick the largest available character to maximize lexicographical order.
  • Use a max-heap (priority queue) for efficient retrieval of the largest character.
  • Track consecutive count of the last used character to enforce repeatLimit.
  • When limit is reached, temporarily use the next largest character to break the sequence.
  • Not all characters need to be used; stop when no valid placement is possible.
  • Time complexity: O(n log k) where n is the length of the result and k is the number of distinct characters.

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