Solving Leetcode Interviews in Seconds with AI: Maximum Number of Operations to Move Ones to the End
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3228" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given a binary string s. You can perform the following operation on the string any number of times: Choose any index i from the string where i + 1 < s.length such that s[i] == '1' and s[i + 1] == '0'. Move the character s[i] to the right until it reaches the end of the string or another '1'. For example, for s = "010010", if we choose i = 1, the resulting string will be s = "000110". Return the maximum number of operations that you can perform. Example 1: Input: s = "1001101" Output: 4 Explanation: We can perform the following operations: Choose index i = 0. The resulting string is s = "0011101". Choose index i = 4. The resulting string is s = "0011011". Choose index i = 3. The resulting string is s = "0010111". Choose index i = 2. The resulting string is s = "0001111". Example 2: Input: s = "00111" Output: 0 Constraints: 1 <= s.length <= 105 s[i] is either '0' or '1'.
Explanation
- The core idea is to greedily move '1's to the right whenever we encounter a '10' pattern. This doesn't prevent any other possible moves later and maximizes moves at each step.
- Maintain an index to iterate through the string, and if we find '10', perform the move. The move can be simulated by decrementing the count of '1's at the current position and incrementing the count of '1's at the end.
- Crucially, instead of actually moving characters in a string (which would be O(n) for each move), we only track the number of '1's at any position. This is the key to making it efficient.
- Runtime: O(n), Storage: O(1)
Code
def max_operations(s: str) -> int:
"""
Calculates the maximum number of operations that can be performed on a binary string.
Args:
s: The binary string.
Returns:
The maximum number of operations.
"""
n = len(s)
operations = 0
ones = 0
for i in range(n - 1):
if s[i] == '1' and s[i + 1] == '0':
operations += 1
s = s[:i] + '0' + s[i+1:]
j = i + 1
while j < len(s) - 1 and s[j+1] == '0':
j+=1
s = s[:j+1] + '1' + s[j+2:]
return operations