algoadvance

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

Clarifying Questions

  1. Case Sensitivity: Should the palindrome check be case-sensitive?
    • Yes, by default, the problem is case-sensitive unless specified otherwise.
  2. Input Constraints: What are the constraints on the length of the array and the strings within it?
    • It is typically reasonable to assume that the array length and each string length will fit within typical problem constraints (e.g., thousands of elements and lengths).

Code

def first_palindromic_string(words):
    for word in words:
        if word == word[::-1]:  # Check if word is a palindrome by comparing it to its reverse
            return word
    return ""

# Example usage:
# words = ["abc", "car", "ada", "racecar", "cool"]
# print(first_palindromic_string(words))  # Output: "ada"

Strategy

  1. Iteration through the Array: Loop through each word in the given list of strings.
  2. Check for Palindrome: For each word, check if the word is a palindrome by comparing the word with its reverse (word[::-1]).
  3. Return the First Palindrome: Once a palindrome is found, immediately return it.
  4. Handle No Palindrome Case: If no palindrome is found after checking all words, return an empty string.

Time Complexity

Try our interview co-pilot at AlgoAdvance.com