Minimum Swaps to Group All 1's Together
Given a string s
, return true
if the s
can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Constraints:
1 <= s.length <= 105
s
consists of lowercase English letters.
Solution
The best approach to solve this problem is using two pointers in opposite directions.
Similar to Valid Palindrome, we will initialize two pointers on the two ends of the string and work our way inside.
We will perform the same palindrome validation by matching the characters at the l
and r
pointers.
If their corresponding characters are different, then we know we must delete one character at one of the l
or r
position.
Then, we can check whether the unprocessed substring (excluding the deleted character) is a palindrome.
In Valid Palindrome, we had implemented is_palindrome
with two pointers, here, we are using an iterative approach for two pointers.
The left pointer is i
and the right pointer is slen - i
, where slen
is len(s) - 1
.
Implementation
1def validPalindrome(self, s: str) -> bool:
2 def isPalindrome(s: str):
3 slen = len(s)-1
4 for i in range(slen//2 + 1):
5 if s[i] != s[slen-i]: return False
6 return True
7
8 l, r = 0, len(s)-1
9 while l < r:
10 if s[l] != s[r]:
11 return isPalindrome(s[l+1:r+1]) or isPalindrome(s[l:r])
12 l += 1
13 r -= 1
14 return True
What is an advantages of top-down dynamic programming vs bottom-up dynamic programming?
Which of the following is a min heap?
Solution Implementation
Which of the following is equvalent to O(3*2^n + n^3 + n!+ log n)?
Which data structure is used to implement recursion?
Recommended Readings
Top Patterns to Conquer the Technical Coding Interview Should the written word bore you fear not A delightful video alternative awaits iframe width 560 height 315 src https www youtube com embed LW8Io6IPYHw title YouTube video player frameborder 0 allow accelerometer autoplay clipboard write encrypted media gyroscope picture in picture
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Got a question? Ask the Teaching Assistant anything you don't understand.
Still not clear? Ask in the Forum, Discord or Submit the part you don't understand to our editors.