Find First Palindromic String in the Array - Problem

Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".

A string is palindromic if it reads the same forward and backward.

Input & Output

Example 1 — Basic Case
$ Input: words = ["abc","car","ada","racecar","cool"]
Output: "ada"
💡 Note: The first palindromic string is "ada". Note that "racecar" is also palindromic but comes after "ada".
Example 2 — No Palindrome
$ Input: words = ["notlob","world"]
Output: ""
💡 Note: None of the strings are palindromic, so return empty string.
Example 3 — Single Character
$ Input: words = ["def","ghi","a"]
Output: "a"
💡 Note: Single character strings are palindromes. "a" is the first palindromic string.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • words[i] consists only of lowercase English letters.

Visualization

Tap to expand
Find First Palindromic String in Array INPUT words array: "abc" [0] "car" [1] "ada" [2] "racecar" [3] "cool" [4] Iterate left to right Find FIRST palindrome Green = First Palindrome ALGORITHM STEPS 1 Loop Through Array for each word in words 2 Check Palindrome word == reverse(word)? 3 Return First Match If palindrome, return it 4 No Match Found Return empty string "" Palindrome Check: "abc" != "cba" X "car" != "rac" X "ada" == "ada" OK Stop here! Return "ada" (skip remaining words) FINAL RESULT First Palindromic String: "ada" Found at index 2 Why "ada" is palindrome: Forward: a-d-a Backward: a-d-a Same! OK Output: "ada" Time: O(n * m) n=words, m=max length Key Insight: The optimal approach iterates through the array once, checking each string against its reverse. We return immediately upon finding the FIRST palindrome, avoiding unnecessary iterations. A string is a palindrome if it equals its reverse: word == word[::-1] (Python) or compare two pointers. TutorialsPoint - Find First Palindromic String in the Array | Optimal Solution
Asked in
Amazon 35 Microsoft 28
24.3K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen