⚔️
DSA Important Questions
  • 😇README
  • 🔫Question List
  • 🧪Formula List
  • 🗒️01 Array
    • ✅Rotate Matrix
    • ✅Max Sum Contiguous Subarray
    • Find Duplicate in Array
    • ✅Merge Intervals
    • ✅Spiral Order Matrix I
    • Repeat and Missing Number Array
    • ✅Merge Overlapping Intervals
    • ✅Set Matrix Zeros
    • ✅Spiral Order Matrix II
    • Largest Number
    • First Missing Integer
    • ✅Pascal Triangle
    • ⭐Max Distance
    • ✅Wavy Array
    • Next Permutation
    • ✅Min Steps in Infinite Grid
    • Flip
    • ⭐Find Permutation
    • ⭐Maximum Absolute Difference
    • ⭐Maximum Unsorted Subarray
    • Reorder Data in Log File
    • ✅Make equal elements Array
  • ➕02 Math
    • ✅Excel Column Number
    • ⭐Excel Column Title
    • ⭐Grid Unique Paths
    • ⭐Power Of Two Integers
    • ✅Next Similar Number
    • ⭐k-th Permutation
  • 🔍03 Binary Search
    • ⭐Median of Array
    • ⭐Square Root of Integer
    • ⭐Rotated Sorted Array Search
    • ⭐Matrix Median
    • Capacity To Ship Packages Within B Days
  • 🧵04 String
    • Implement StrStr
    • ⭐Integer to Roman
    • ⭐Roman to Integer
    • Length of Last Word
    • ⭐atoi
    • ⭐Valid IP Addresses
    • ⭐Compare Version Numbers
    • ⭐Longest Palindromic Substring
    • Count And Say
    • Reverse the String
    • Power of 2
    • 🚧KMP: Minimum Characters Required to Make a String Palindromic
    • ⭐Convert to Palindrome
    • Bulls and Cows
  • 1️⃣05 Bit Manipulation
    • Reverse Bits
    • Single Number
    • ⭐Divide Integers
    • ⭐Single Number II
    • ⭐Count Total Set Bits
    • ⭐Palindromic Binary Representation
  • ✌️06 Two Pointers
    • Merge Two Sorted Lists II
    • ⭐3 Sum
    • Remove Duplicates from sorted Array
    • ⭐Container With Most Water
    • Remove Element from Array
    • ⭐Max Continuous Series of 1s
    • Pair With Given Difference
    • ⭐Maximum Ones After Modification
  • 🔗07 Linked List
    • Swap List Nodes in Pairs
    • Rotate List
    • ⭐Reorder List
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted List
    • Add Two Numbers as Lists
    • Remove Nth Node from List End
    • ⭐List Cycle
    • Intersection of Linked Lists
    • ⭐Reverse Linked List II
    • Palindrome List
    • ⭐K reverse linked list
    • ⭐Reverse Alternate K Nodes
    • ⭐Kth Node From Middle
    • ⭐Sort Binary Linked List
    • ⭐Even Reverse
  • 📚08 Stacks and Queues
    • ⭐Rain Water Trapping
    • Generate all Parentheses
    • ⭐Largest Rectangle in Histogram
    • ⭐Min Stack
    • Redundant Braces
    • Nearest Smaller Element
    • ⭐First non-repeating character in a stream of characters
    • ✅Balanced Parantheses!
  • 🔙09 Backtracking
    • ⭐Kth Permutation Sequence
    • ⭐Combination Sum
    • Combination Sum II
    • ⭐NQueens
    • Combinations
    • ⭐Subsets II
    • Subset
    • Palindrome Partitioning
  • 💱10 Hashing
    • ⭐Longest Consecutive Sequence
    • ⭐4 Sum
    • ⭐Anagrams
    • ⭐Points on the Straight Line
    • 2 Sum
    • ⭐Valid Sudoku
    • Copy List
    • Longest Substring Without Repeat
  • 🗻11 Heaps & Maps
    • Merge K Sorted Lists
    • ⭐LRU Cache
    • ⭐Inversions
    • Distinct Numbers in Window
  • 🌳12 Tree Data Structure
    • ✅Inorder Traversal
    • ⭐Recover Binary Search Tree
    • ⭐Inorder Traversal of Cartesian Tree
    • ⭐Least Common Ancestor
    • ⭐Construct Binary Tree From Inorder And Preorder
    • Flatten Binary Tree to Linked List
    • Valid Binary Search Tree
    • ✅Preorder Traversal
    • ⭐Binary Tree From Inorder And Postorder
    • Balanced Binary Tree
    • ✅Sorted Array To Balanced BST
    • Symmetric Binary Tree
    • ✅Postorder Traversal
    • ⭐Populate Next Right Pointers Tree
    • Identical Binary Trees
    • BST Iterator
    • ZigZag Level Order Traversal BT
    • Path Sum
    • Next Pointer Binary Tree
    • Min Depth of Binary Tree
    • Root to Leaf Paths With Sum
    • ⭐Kth Smallest Element in Tree
    • ⭐2-Sum Binary Tree
    • Vertical Order traversal of Binary Tree
    • ⭐Diagonal Traversal
    • Cousins in Binary Tree
    • Path to Given Node
    • Remove Half Nodes
    • Merge two Binary Tree
    • ⭐Burn a Tree
    • Nodes at Distance K
    • Vertical Sum of a Binary Tree
    • Covered / Uncovered Nodes
  • 13 Dynamic Programming
    • Ugly Number II
    • Coin Change
    • 0 - 1 Knapsack Problem
    • Permutation Coefficient
  • 14 Greedy Algorithm
    • ⭐Gas Station
    • ⭐Majority Element
    • ⭐Distribute Candy
    • ⭐Highest Product
    • Assign Mice to Holes
    • ⭐Meeting rooms
  • 👨‍👩‍👧‍👦15 Graph
    • Clone Graph
    • Word Search Board
    • ⭐Stepping Numbers
    • Black Shapes
    • Knight On Chess Board
    • ❌Smallest Multiple With 0 and 1
    • ⭐Commutable Islands
    • Possibility of finishing all courses given pre-requisites
    • ❌Valid Path
    • Cycle in Directed Graph
    • ❌Cycle in Undirected Graph
Powered by GitBook
On this page
  1. 04 String

KMP: Minimum Characters Required to Make a String Palindromic

PreviousPower of 2NextConvert to Palindrome

Last updated 3 years ago

Thoughts
  • 0:00 The name of the questions sounds like one of those that I clearly won't be able to solve on my own. I'll just give it a try once and see if I should go straight to the solution.

  • 36:00 I spent a lot more time than I wanted to. I have a solution that should work but it's giving the wrong answer. .

  • 45:00 So the problem was that I read the question wrong and thought that we can insert characters at both the beginning and the end. Let's see if it will work now that I know this.

  • Ok, so my solution was correct but not optimal. I'm surprised I was able to solve this at all. I'll paste it here as a brute-force solution and see the provided solution.

  • 50:00 According to the hint, I need to learn KMP. I'll go ahead and watch a video on that.

  • 54:00 According to Need Code, KMP is a very very very hard problem. I don't have time right now as I'm behind schedule, so i'll defer it for now and move to the next question.

Brute Force

int getMinRes(pair<int, int> palindrome, int size, int res) {
    if(palindrome.first == 0)
        res = min(res, size - palindrome.second - 1);
    // if insertion at end was allowed then
    // if(palindrome.second == size - 1)
    //     res = min(res, palindrome.first);
    
    return res;
}
pair<int, int> getPalindromeAt(const string &A, int begin, int end) {
    pair<int, int> res;
    while(begin >= 0 && end < A.size()) {
        if(A[begin] == A[end])
            res.first = begin, res.second = end;
        else    
            break;
        begin--, end++;
    }
    return res;    
}

int Solution::solve(string A) {
    pair<int, int> palindrome;
    int res = INT_MAX;
    for(int i = 0; i < A.size(); i++) {
        palindrome = getPalindromeAt(A, i, i);
        res = getMinRes(palindrome, A.size(), res);
        
        if(i + 1 < A.size()) {
            palindrome = getPalindromeAt(A, i, i + 1);
            res = getMinRes(palindrome, A.size(), res);    
        }
    }
    return res;
}

The getPalindromeAt() is the same as the one used in the solution.

🧵
🚧
Longest Palindrome Substring
Time to take it to OnlineGDB
Minimum Characters required to make a String Palindromic - InterviewBitInterviewBit
Logo