Palindrome Index

  • + 0 comments

    O(n) c++ solution:

    int palindromeIndex(string s) {
        size_t left{}, right{s.size() - 1};
    		// last occurrence 
        std::pair<int, int> index{};
        int cursor{-1};
    		// track direction pointer is moving in case of char mismatch
    		// 0: left++
    		// 1: right--
    		// 2: no solution found left-right 
        size_t counter{};
        while(left < right)
        {
            if(s[left] == s[right])
            {
                left++;
                right--;
            }
            else {
                if(counter >= 2)
                    return -1;
                else if(counter == 1)
                {
                    left = index.first;
                    right = index.second;
                    cursor = right;
                    right--;        
                }
                else {
                    index = {left, right};
                    cursor = left;
                    left++;
                }
                counter++;
            }
        }
            
        return cursor;
    }