J.P. Morgan Software Engineer Interview Experience — Minimizing a String by Removing AB and BB

J.P. Morgan·Software Engineer·Sep 2026
Online Assessmenteasy

[Problem description]
Given a string seq consisting only of the characters 'A' and 'B'.
You can repeatedly perform the following operation:
Delete any occurrence of the substring "AB" or "BB".
After deletion, the remaining parts of the string are joined together.
Your task is to determine the minimum possible length of the string after any number of valid deletions.
Note: A substring is a contiguous sequence of characters.
[Example]
Input: seq = "BABBA"
Output: 1
Explanation:
Delete the substring "AB" starting at index 1: "BABBA" -> "BBA"
Delete the substring "BB" starting at index 0: "BBA" -> "A"
No more operations are possible, and the minimum length is 1.
[Constraints]
1 <= length of seq <= 2 * 10^5
[Approach]
This problem can be solved in O(N) time using a stack.
Since "AB" and "BB" can be removed, a 'B' can be eliminated whenever it has an 'A' or another 'B' before it.
We traverse the string seq:
If the character is 'A', push it directly onto the stack.
If the character is 'B':
If the stack is not empty, its top element, whether 'A' or 'B', can pair with this character to form "AB" or "BB" and be removed, so pop the top element.
If the stack is empty, there is no preceding character to pair with this 'B', so it cannot be removed. Push it onto the stack.
After the traversal, the elements remaining in the stack are the characters that cannot be removed. The stack size is the minimum remaining length.
[Code implementation (Python)]

def solution(seq):
    stack = []
    for char in seq:
        if char == 'A':
            stack.append('A')
        else: # char == 'B'
            if stack:
                stack.pop()
            else:
                stack.append('B')
    return len(stack)

Published

Curated and edited by PracHub

Practice the questions from this interview

Discussion

Sign in to join the discussion. The author is notified of every comment.

Loading comments…

Interview at a glance

Company
J.P. Morgan
Role
Software Engineer
Rounds
Online Assessment
Difficulty
easy
Interview date
Sep 2026
Questions from this interview
1 question

Real J.P. Morgan interview experiences

First-hand reports from J.P. Morgan candidates — the rounds, the questions they were asked, and how it went.

All 11 J.P. Morgan interview experiences