Similar Problems

Similar Problems not available

Find First Palindromic String In The Array - Leetcode Solution

Companies:

LeetCode:  Find First Palindromic String In The Array Leetcode Solution

Difficulty: Easy

Topics: string array two-pointers  

Problem Statement:

Given an array of strings strs, find the first palindromic string in the array. A palindromic string is a string that remains the same when its characters are reversed.

If there is no palindromic string in the array, return the empty string "".

Example 1:

Input: strs = ["abcd","efgh","ijkl","mnopnm"] Output: "mnopnm"

Example 2:

Input: strs = ["abc","def","ghi"] Output: ""

Solution:

To find a palindromic string in the array, we can iterate over each string and check if it's a palindrome or not. If a string is a palindrome, we return it as a result.

Here's how we can implement this in Python:

def is_palindrome(s): # Check if the string s is a palindrome return s == s[::-1]

def find_first_palindrome(strs): # Iterate over each string for s in strs: # Check if the string s is a palindrome if is_palindrome(s): return s

# If no string is a palindrome, return an empty string
return ""

Explanation:

We define a function is_palindrome that checks if a given string is a palindrome or not. It does this by comparing the reversed string with the original string.

Then we define our main function find_first_palindrome that takes an array of strings as input. It iterates over each string in the array and checks if it's a palindrome or not using the is_palindrome function. If a palindrome is found, it returns the string. If no palindromic string is found, it returns an empty string.

Finally, we can test our function with the given test cases:

print(find_first_palindrome(["abcd","efgh","ijkl","mnopnm"]))

Output: "mnopnm"

print(find_first_palindrome(["abc","def","ghi"]))

Output: ""

Find First Palindromic String In The Array Solution Code

1