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

def validPalindrome(self, s: str) -> bool:
    def isPalindrome(s: str):
        slen = len(s)-1
        for i in range(slen//2 + 1):
            if s[i] != s[slen-i]: return False
        return True
    
    l, r = 0, len(s)-1
    while l < r:
        if s[l] != s[r]:
            return isPalindrome(s[l+1:r+1]) or isPalindrome(s[l:r])
        l += 1
        r -= 1
    return True

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

What's the output of running the following function using the following tree as input?

1def serialize(root):
2    res = []
3    def dfs(root):
4        if not root:
5            res.append('x')
6            return
7        res.append(root.val)
8        dfs(root.left)
9        dfs(root.right)
10    dfs(root)
11    return ' '.join(res)
12
1import java.util.StringJoiner;
2
3public static String serialize(Node root) {
4    StringJoiner res = new StringJoiner(" ");
5    serializeDFS(root, res);
6    return res.toString();
7}
8
9private static void serializeDFS(Node root, StringJoiner result) {
10    if (root == null) {
11        result.add("x");
12        return;
13    }
14    result.add(Integer.toString(root.val));
15    serializeDFS(root.left, result);
16    serializeDFS(root.right, result);
17}
18
1function serialize(root) {
2    let res = [];
3    serialize_dfs(root, res);
4    return res.join(" ");
5}
6
7function serialize_dfs(root, res) {
8    if (!root) {
9        res.push("x");
10        return;
11    }
12    res.push(root.val);
13    serialize_dfs(root.left, res);
14    serialize_dfs(root.right, res);
15}
16

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More