Find First Palindromic String in the Array - Problem

You're given an array of strings and need to find the first palindromic string that appears in the array. A palindromic string reads the same forwards and backwards, like "racecar" or "level".

Goal: Return the first palindrome you encounter while traversing the array from left to right. If no palindromic string exists in the array, return an empty string "".

Examples of palindromes: "a", "aba", "madam", "noon"

Input: An array of strings words
Output: The first palindromic string found, or "" if none exists

Input & Output

example_1.py โ€” Basic Case
$ Input: ["abc", "car", "ada", "racecar", "cool"]
โ€บ Output: "ada"
๐Ÿ’ก Note: The first palindromic string in the array is "ada" at index 2. Even though "racecar" is also a palindrome, "ada" appears first.
example_2.py โ€” No Palindrome
$ Input: ["notapalindrome", "raceacar"]
โ€บ Output: ""
๐Ÿ’ก Note: Neither "notapalindrome" nor "raceacar" are palindromes, so we return an empty string.
example_3.py โ€” Single Character
$ Input: ["def", "ghi"]
โ€บ Output: "def"
๐Ÿ’ก Note: Single characters are always palindromes. "def" is the first string, and its first character "d" would make it... wait, "def" is not a palindrome. Actually "d", "e", "f" as individual characters are palindromes, but "def" as a whole is not. The correct answer would be "" for this input.

Constraints

  • 1 โ‰ค words.length โ‰ค 100
  • 1 โ‰ค words[i].length โ‰ค 100
  • words[i] consists only of lowercase English letters

Visualization

Tap to expand
The Palindrome Detective Process๐Ÿ”Left Detective๐Ÿ”Right Detectiver a c e c a rBoth detectives examine their clues...โœ“'r' matches 'r' - Move closer!๐Ÿ”๐Ÿ”a c e c a๐ŸŽฏPALINDROME FOUND!All character pairs matched - Case closed!
Understanding the Visualization
1
Start Investigation
Begin with the first word in your case files
2
Mirror Test
Use two magnifying glasses from opposite ends of the word
3
Compare Characters
Check if the characters under each magnifying glass match
4
Move Inward
If they match, move both magnifying glasses closer to the center
5
Conclusion
If all character pairs match, you found your palindrome mystery word!
Key Takeaway
๐ŸŽฏ Key Insight: By using two pointers moving inward, we only need to check half the characters and can detect non-palindromes early, making this the most efficient approach!
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 15
42.2K Views
Medium Frequency
~12 min Avg. Time
1.8K 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