2108. Find First Palindromic String in the Array

Problem Description

The problem asks us to find the first string in an array that is palindromic. A palindromic string is a string that reads the same forwards as it does backwards. For example, 'racecar' is a palindrome because reversing it gives the same word. We are given an array of strings and we need to check these strings one by one to see if any of them is a palindrome. The first palindromic string we come across should be returned. If we go through the whole array and find no palindromic strings, we return an empty string, represented by "".


To solve this problem, the natural approach is to iterate over each string in the array and check whether it is a palindrome. If we find a palindrome, we return it immediately. To check if a string is a palindrome, we need to read it from the front and back and compare each character to see if they match. A convenient way to reverse a string in Python is to use the slicing syntax string[::-1], which creates a new string that is the reverse of the original.

Given that we want to find the first palindromic string, we can use Python's next function combined with a generator expression to efficiently look for it. The generator expression creates an iterator that will only process each string as needed, which is both memory efficient and potentially time-saving if the palindromic string is found early in the array. The next function then tries to get the first element from this generator, and if none is found, it returns a default value, which in this case is the empty string "". This succinctly solves the problem without needing extra loops or conditionals to handle the case where no palindromic string is found.

Learn more about Two Pointers patterns.

Not Sure What to Study? Take the 2-min Quiz to Find Your Missing Piece:

What's the output of running the following function using input 56?

2    '2': 'abc',
3    '3': 'def',
4    '4': 'ghi',
5    '5': 'jkl',
6    '6': 'mno',
7    '7': 'pqrs',
8    '8': 'tuv',
9    '9': 'wxyz',
12def letter_combinations_of_phone_number(digits):
13    def dfs(path, res):
14        if len(path) == len(digits):
15            res.append(''.join(path))
16            return
18        next_number = digits[len(path)]
19        for letter in KEYBOARD[next_number]:
20            path.append(letter)
21            dfs(path, res)
22            path.pop()
24    res = []
25    dfs([], res)
26    return res
1private static final Map<Character, char[]> KEYBOARD = Map.of(
2    '2', "abc".toCharArray(),
3    '3', "def".toCharArray(),
4    '4', "ghi".toCharArray(),
5    '5', "jkl".toCharArray(),
6    '6', "mno".toCharArray(),
7    '7', "pqrs".toCharArray(),
8    '8', "tuv".toCharArray(),
9    '9', "wxyz".toCharArray()
12public static List<String> letterCombinationsOfPhoneNumber(String digits) {
13    List<String> res = new ArrayList<>();
14    dfs(new StringBuilder(), res, digits.toCharArray());
15    return res;
18private static void dfs(StringBuilder path, List<String> res, char[] digits) {
19    if (path.length() == digits.length) {
20        res.add(path.toString());
21        return;
22    }
23    char next_digit = digits[path.length()];
24    for (char letter : KEYBOARD.get(next_digit)) {
25        path.append(letter);
26        dfs(path, res, digits);
27        path.deleteCharAt(path.length() - 1);
28    }
1const KEYBOARD = {
2    '2': 'abc',
3    '3': 'def',
4    '4': 'ghi',
5    '5': 'jkl',
6    '6': 'mno',
7    '7': 'pqrs',
8    '8': 'tuv',
9    '9': 'wxyz',
12function letter_combinations_of_phone_number(digits) {
13    let res = [];
14    dfs(digits, [], res);
15    return res;
18function dfs(digits, path, res) {
19    if (path.length === digits.length) {
20        res.push(path.join(''));
21        return;
22    }
23    let next_number = digits.charAt(path.length);
24    for (let letter of KEYBOARD[next_number]) {
25        path.push(letter);
26        dfs(digits, path, res);
27        path.pop();
28    }

Solution Approach

The solution uses a generator expression that iterates over the list of words. This expression takes each word w in words and checks if it is a palindrome by comparing the word to its reverse, w[::-1]. This reversal is done using Python's slice notation, which, when provided with [::-1], starts from the end of the string and steps backwards, effectively reversing it.

Here's a step by step breakdown of the algorithm:

  1. The generator expression (w for w in words if w == w[::-1]) creates an iterator. This iterator goes through each string w in the words array and yields it if and only if the string is the same as its reversed version. This leverages the fact that a palindrome is by definition a string that does not change when its characters are reversed.

  2. Python’s next function is used to retrieve the next item from the iterator created by the generator expression. In this context, it serves to fetch the first palindrome it encounters while iterating over the generator.

  3. The second argument to the next function is "", which is the default value to return in case the generator does not yield any items, i.e., if there are no palindromic strings in the array.

This solution is elegant and efficient:

  • It avoids the need for an explicit loop to iterate over the elements and check them one by one.
  • It uses lazy evaluation: the generator expression is only evaluated up to the point where the first palindrome is found, which can save time if a palindrome occurs early in the list.
  • There's no need for additional memory to store intermediate results, as the generator doesn't create a temporary list of palindromes, unlike, for example, a list comprehension would.

Overall, the use of next and a generator expression allows for an efficient and concise solution to the problem.

Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

Depth first search can be used to find whether two components in a graph are connected.

Example Walkthrough

Let's go through a small example to illustrate the solution approach step by step. We have the following array of strings:

1words = ["hello", "world", "racecar", "level", "sample"]

We are looking to find the first string that is palindromic.

  1. The first string we check is "hello". We reverse it to see if it matches its original form: "olleh". Since "hello" is not equal to "olleh", we continue to the next word.

  2. The next string is "world". Reversed, it is "dlrow", which again does not equal "world". So we move on.

  3. We come to "racecar" and reverse it. The reversed version is "racecar" — it matches exactly! Since we found a palindrome, we don't need to check any further; we return "racecar".

To represent this process programmatically:

1# use generator expression to iterate over each word and check if it is a palindrome
2palindromic_string = next((w for w in words if w == w[::-1]), "")
3print(palindromic_string)  # This will output "racecar"

The generator expression (w for w in words if w == w[::-1]) iterates through each word in the words array and yields the word if it is a palindrome. The next function is then used to get the first item from the iterator. If no palindromic string is found, it will return the default specified by the second argument, which is "".

In this example, the next function does not need to go through the entire list since it returns as soon as it finds the palindromic string "racecar". Thus, the generator stops iterating after the third element, demonstrating efficient use of resources. If racecar had not been a palindrome, the iteration would continue to "level", which is the next palindromic string, or until the list was exhausted.

Solution Implementation

1from typing import List  # Import List from the typing module for type hinting
3class Solution:
4    def firstPalindrome(self, words: List[str]) -> str:
5        """
6        Finds the first palindromic word from a list of words.
8        Args:
9        words (List[str]): A list of strings.
11        Returns:
12        str: The first palindromic word in the list of words, or an
13             empty string if there is no such word.
14        """
15        # Iterate through each word in the list
16        for word in words:
17            # Check if the current word is the same as its reversed copy
18            if word == word[::-1]:
19                return word  # Return the palindromic word
21        # Return an empty string if no palindromic word is found
22        return ""
24# Example usage:
25# sol = Solution()
26# print(sol.firstPalindrome(["abc", "car", "ada", "racecar", "cool"]))
27# This will print "ada" as it is the first palindrome in the list
1class Solution {
2    // This method finds the first palindromic string in an array.
3    public String firstPalindrome(String[] words) {
4        // Iterate over each word in the array.
5        for (String word : words) {
6            // Assume initially that each word could be a palindrome.
7            boolean isPalindrome = true;
8            // Use two pointers to compare characters from the front and the back.
9            for (int i = 0, j = word.length() - 1; i < j; ++i, --j) {
10                // If corresponding characters do not match, the word is not a palindrome.
11                if (word.charAt(i) != word.charAt(j)) {
12                    isPalindrome = false;
13                    // No need to check remaining characters if a mismatch is found.
14                    break;
15                }
16            }
17            // If the word is a palindrome, return it.
18            if (isPalindrome) {
19                return word;
20            }
21        }
22        // Return an empty string if no palindromic strings are found.
23        return "";
24    }
1#include <vector>
2#include <string>
4class Solution {
6    // Function to find the first palindrome in a list of words.
7    string firstPalindrome(vector<string>& words) {
8        // Iterate over each word in the vector.
9        for (const auto& word : words) {
10            // Assume initially that the word is a palindrome.
11            bool isPalindrome = true;
13            // Check each character from the start and the end of the word moving towards the center.
14            for (int start = 0, end = word.size() - 1; start < end; ++start, --end) {
15                // If the characters do not match, the word is not a palindrome.
16                if (word[start] != word[end]) {
17                    isPalindrome = false;
18                    break; // Exit the loop early as we already know it's not a palindrome.
19                }
20            }
22            // If the word is a palindrome, return it.
23            if (isPalindrome) {
24                return word;
25            }
26        }
28        // If no palindrome is found, return an empty string.
29        return "";
30    }
1// This function searches for the first palindrome string within an array of words.
2// A palindrome is a word that reads the same backward as forward.
3// @param words - An array of strings to be checked.
4// @returns The first palindrome string if one exists, or an empty string if none is found.
5function firstPalindrome(words: string[]): string {
6    // Loop through each word in the array to check for palindromes.
7    for (const word of words) {
8        // Initialize pointers for the start and end of the word.
9        let startIndex = 0;
10        let endIndex = word.length - 1;
12        // Move the pointers towards the center of the word.
13        while (startIndex < endIndex) {
14            // Check if the characters at the start and end pointers do not match.
15            if (word[startIndex] !== word[endIndex]) {
16                // If they do not match, break from the loop; the word is not a palindrome.
17                break;
18            }
19            // Move the pointers closer to the center.
20            startIndex++;
21            endIndex--;
22        }
24        // If the pointers have met or crossed, the word is a palindrome.
25        if (startIndex >= endIndex) {
26            // Return the current palindrome word.
27            return word;
28        }
29    }
31    // If no palindrome is found in the array, return an empty string.
32    return '';
Not Sure What to Study? Take the 2-min Quiz:

Is the following code DFS or BFS?

1void search(Node root) {
2  if (!root) return;
3  visit(root);
4  root.visited = true;
5  for (Node node in root.adjacent) {
6    if (!node.visited) {
7      search(node);
8    }
9  }

Time and Space Complexity

Time Complexity

The provided code checks each word in the list to see if it is a palindrome. The time it takes to check if a word is a palindrome depends on the length of the word, as it requires comparing characters from the beginning and the end towards the center.

To determine the time complexity, let n be the number of words in the list and k be the average length of these words.

Checking if a single word is a palindrome has a complexity of O(k) because we need to compare about half of the characters (in the worst case) to their counterparts on the other side of the word.

As we use a generator expression with the next function to find the first palindrome, the worst-case scenario happens when the palindrome is the last word in the list or there is no palindrome at all. Therefore, we might need to check every word. In this case, the time complexity would be O(n * k), as we perform an O(k) operation n times.

Space Complexity

The space complexity of the algorithm is O(1).

This is because it uses a constant amount of additional space regardless of the input size. The generator expression does not create an additional list in memory; it simply iterates over the existing list, and string slicing creates a new string, but since we are only interested in one word at a time, this does not accumulate with the number of words. Thus, the space used does not scale with the number of words n or their lengths k.

Learn more about how to find time and space complexity quickly using problem constraints.

Fast Track Your Learning with Our Quick Skills Quiz:

Which of the following is the prefix sum of array [1, 2, 3, 4, 5]?

Recommended Readings

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.

TA 👨‍🏫