We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find First Palindromic String in the Array

Number: 2231

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

Given an array of strings, return the first palindromic string in the array. A string is palindromic if it reads the same forward and backward. If there is no such string, return an empty string.


Key Insights

  • Traverse the array of strings in order.
  • Check each string to see if it is a palindrome by comparing characters.
  • Return the first string that is a palindrome.
  • If no palindromic string is found, return an empty string.

Space and Time Complexity

Time Complexity: O(n * m), where n is the number of strings and m is the average length of a string. Space Complexity: O(1) using two pointers (or O(m) if creating a reversed copy of the string).


Solution

Iterate through each string in the array. For each string, determine if it is a palindrome by either:

  1. Comparing characters from the start and end using two pointers, or
  2. Reversing the string and checking if it matches the original. As soon as a palindromic string is found, return it. If the end of the array is reached without finding any palindrome, return an empty string.

Code Solutions

# Define a function to return the first palindromic string from a list of words
def first_palindrome(words):
    # Iterate over each word in the list
    for word in words:
        # Check if the word is the same when reversed
        if word == word[::-1]:
            return word  # Return the first palindrome found
    return ""  # Return empty string if no palindrome exists

# Example usage
words = ["abc", "car", "ada", "racecar", "cool"]
print(first_palindrome(words))  # Expected output: "ada"
← Back to All Questions