Palindrome pair in an array of words (or strings)
Last Updated :
23 Jul, 2025
Given an array of strings arr[] of size n, the task is to find if there exists two strings arr[i] and arr[j] such that arr[i]+arr[j] is a palindrome i.e the concatenation of string arr[i] and arr[j] results into a palindrome.
Examples:
Input: arr[] = ["geekf", "geeks", "or", "keeg", "abc", "bc"]
Output: True
Explanation: Strings "geekf" and "keeg" can be concatenated to form a palindromic string "geekfkeeg" .
Input: arr[] = ["abc", "xyxcba", "geekst", "or", "keeg", "bc"]
Output: True
Explanation: Strings "abc" and "xyxcba" can be concatenated to form a palindromic string "abcxyxcba" .
Input: arr[] = ["abc", "ab", "xyz"]
Output: False
Explanation: No palindromic string can be formed by concatenating any two of the given strings.
[Naive Approach] Using Nested Loop
The idea is to iteratively generate all possible pairs of strings using the nested loops and check if any of them is a palindrome.
C++
// C++ program to check if the given array
// contains a plaindromic pair of strings
#include<bits/stdc++.h>
using namespace std;
// Function to check if a string is palindrome
bool isPalindrome(string &s) {
int n = s.length();
// compare each character from starting
// with its corresponding character from last
for (int i = 0; i < n/2; i++ )
if (s[i] != s[n-i-1])
return false;
return true;
}
// Function to check if a palindrome pair exists
bool palindromePair(vector<string> &arr) {
// Consider each pair one by one
for (int i = 0; i < arr.size(); i++) {
for (int j = i + 1; j< arr.size(); j++) {
// concatenate both strings
string str = arr[i] + arr[j];
// check if str is palindrome
if (isPalindrome(str))
return true;
// check for other combination
str = arr[j] + arr[i];
if (isPalindrome(str))
return true;
}
}
return false;
}
int main() {
vector <string> arr = {"geekf", "geeks", "or", "keeg", "abc", "bc"};
if(palindromePair(arr))
cout << "True";
else
cout << "False";
return 0;
}
Java
// Java program to check if the given array
// contains a palindromic pair of strings
import java.util.*;
class GfG {
// Function to check if a string is palindrome
static boolean isPalindrome(String s) {
int n = s.length();
// compare each character from starting
// with its corresponding character from last
for (int i = 0; i < n / 2; i++)
if (s.charAt(i) != s.charAt(n - i - 1))
return false;
return true;
}
// Function to check if a palindrome pair exists
static boolean palindromePair(String[] arr) {
// Consider each pair one by one
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
// concatenate both strings
String str = arr[i] + arr[j];
// check if str is palindrome
if (isPalindrome(str))
return true;
// check for other combination
str = arr[j] + arr[i];
if (isPalindrome(str))
return true;
}
}
return false;
}
public static void main(String[] args) {
String[] arr = {"geekf", "geeks", "or", "keeg", "abc", "bc"};
if (palindromePair(arr))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python program to check if the given array
# contains a palindromic pair of strings
# Function to check if a string is palindrome
def isPalindrome(s):
n = len(s)
# compare each character from starting
# with its corresponding character from last
for i in range(n // 2):
if s[i] != s[n - i - 1]:
return False
return True
# Function to check if a palindrome pair exists
def palindromePair(arr):
# Consider each pair one by one
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
# concatenate both strings
strVal = arr[i] + arr[j]
# check if str_val is palindrome
if isPalindrome(strVal):
return True
# check for other combination
strVal = arr[j] + arr[i]
if isPalindrome(strVal):
return True
return False
if __name__ == "__main__":
arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"]
if palindromePair(arr):
print("True")
else:
print("False")
C#
// C# program to check if the given array
// contains a palindromic pair of strings
using System;
class GfG {
// Function to check if a string is palindrome
static bool isPalindrome(string s) {
int n = s.Length;
// compare each character from starting
// with its corresponding character from last
for (int i = 0; i < n / 2; i++)
if (s[i] != s[n - i - 1])
return false;
return true;
}
// Function to check if a palindrome pair exists
static bool palindromePair(string[] arr) {
// Consider each pair one by one
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
// concatenate both strings
string str = arr[i] + arr[j];
// check if str is palindrome
if (isPalindrome(str))
return true;
// check for other combination
str = arr[j] + arr[i];
if (isPalindrome(str))
return true;
}
}
return false;
}
static void Main() {
string[] arr = { "geekf", "geeks", "or", "keeg", "abc", "bc" };
if (palindromePair(arr))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to check if the given array
// contains a palindromic pair of strings
// Function to check if a string is palindrome
function isPalindrome(s) {
let n = s.length;
// compare each character from starting
// with its corresponding character from last
for (let i = 0; i < Math.floor(n / 2); i++)
if (s[i] !== s[n - i - 1])
return false;
return true;
}
// Function to check if a palindrome pair exists
function palindromePair(arr) {
// Consider each pair one by one
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
// concatenate both strings
let str = arr[i] + arr[j];
// check if str is palindrome
if (isPalindrome(str))
return true;
// check for other combination
str = arr[j] + arr[i];
if (isPalindrome(str))
return true;
}
}
return false;
}
// Driver code
let arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"];
if (palindromePair(arr))
console.log("True");
else
console.log("False");
Time Complexity: O(n2 * k), here n is the number of words in the array arr[] and k is the length of the longest concatenated string.
Auxiliary Space: O(1)
[Expected Approach] Using Trie Data Structure
The idea is to use Trie Data Structure to store all the strings and efficiently search for palindromic pairs. To do so, initialize an empty Trie and store the strings of arr[] in reverse order. Also for each index ind of string arr[i], store if substring arr[i][0] to arr[i][ind] is a palindrome.
Now, traverse the array arr[] again, and for each string arr[i], check if it is present in Trie, if so, return true. Otherwise, if the string arr[i] exists partially in Trie, check if remaining part is palindrome or not, if so, return true, else move to the next string. If no pair of string is found, return false.
C++
// C++ program to check if the given array
// contains a plaindromic pair of strings
#include<bits/stdc++.h>
using namespace std;
// Trie node
class TrieNode {
public:
// pointer array for 26 letters
vector<TrieNode*> children;
//indices of palindromic words
vector<int> indices;
// index of word in array
int idx;
TrieNode() : idx(-1) {
// initialize children array to NULL
children.resize(26, nullptr);
}
};
// Function to check if a string is palindrome
bool isPalindrome(string str, int i, int j) {
// compare each character from starting
// with its corresponding character from last
while (i < j) {
if (str[i] != str[j])
return false;
i++, j--;
}
return true;
}
// If not present, inserts reverse of word into Trie. If
// the word is prefix of a Trie node, just mark leaf node
void insert(TrieNode* root, string word, int idx) {
TrieNode *node = root;
// Start traversing word from the last
for (int i = word.length() - 1; i >= 0; i--) {
// If current word is palindrome till this
// i, store index of current word.
if (isPalindrome(word, 0, i))
(node->indices).push_back(idx);
// If it is not available in Trie
// then store it
int index = word[i] - 'a';
if (!node->children[index])
node->children[index] = new TrieNode();
// move to new TrieNode
node = node->children[index];
}
node->idx = idx;
node->indices.push_back(idx);
}
// Returns true if word presents in Trie, else false
bool search(TrieNode *root, string word, int idx) {
TrieNode *node = root;
for (int i = 0; i < word.length() && node; i++) {
int index = word[i] - 'a';
// If it is present also check upto
// which index it is palindrome
if (node->idx >= 0 && node->idx != idx &&
isPalindrome(word, i, word.size()-1))
return true;
node = node->children[index];
}
if(node) {
for (int i : node->indices) {
if (idx != i)
return true;
}
}
return false;
}
// Function to check if a palindrome pair exists
bool palindromePair(vector<string> &arr) {
// Construct trie
TrieNode *root = new TrieNode();
for (int i = 0; i < arr.size(); i++)
insert(root, arr[i], i);
// Search for different keys
for (int i = 0; i < arr.size(); i++) {
if (search(root, arr[i], i))
return true;
}
return false;
}
int main() {
vector <string> arr = {"geekf", "geeks", "or", "keeg", "abc", "bc"};
if(palindromePair(arr))
cout << "True";
else
cout << "False";
return 0;
}
Java
// Java program to check if the given array
// contains a palindromic pair of strings
import java.util.*;
class TrieNode {
// pointer array for 26 letters
TrieNode[] children;
// indices of palindromic words
List<Integer> indices;
// index of word in array
int idx;
TrieNode() {
this.idx = -1;
// initialize children array to NULL
this.children = new TrieNode[26];
this.indices = new ArrayList<>();
}
}
class GFG {
// Function to check if a string is palindrome
static boolean isPalindrome(String str, int i, int j) {
// compare each character from starting
// with its corresponding character from last
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++; j--;
}
return true;
}
// If not present, inserts reverse of word into Trie.
// If the word is prefix of a Trie node, just mark leaf node
static void insert(TrieNode root, String word, int idx) {
TrieNode node = root;
// Start traversing word from the last
for (int i = word.length() - 1; i >= 0; i--) {
// If current word is palindrome till this
// i, store index of current word.
if (isPalindrome(word, 0, i))
node.indices.add(idx);
// If it is not available in Trie
// then store it
int index = word.charAt(i) - 'a';
if (node.children[index] == null)
node.children[index] = new TrieNode();
// move to new TrieNode
node = node.children[index];
}
node.idx = idx;
node.indices.add(idx);
}
// Returns true if word presents in Trie, else false
static boolean search(TrieNode root, String word, int idx) {
TrieNode node = root;
for (int i = 0; i < word.length() && node != null; i++) {
int index = word.charAt(i) - 'a';
// If it is present also check upto
// which index it is palindrome
if (node.idx >= 0 && node.idx != idx &&
isPalindrome(word, i, word.length()-1))
return true;
node = node.children[index];
}
if (node != null) {
for (int i : node.indices) {
if (idx != i)
return true;
}
}
return false;
}
// Function to check if a palindrome pair exists
static boolean palindromePair(String[] arr) {
// Construct trie
TrieNode root = new TrieNode();
for (int i = 0; i < arr.length; i++)
insert(root, arr[i], i);
// Search for different keys
for (int i = 0; i < arr.length; i++) {
if (search(root, arr[i], i))
return true;
}
return false;
}
public static void main(String[] args) {
String[] arr = {"geekf", "geeks", "or", "keeg", "abc", "bc"};
if (palindromePair(arr))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python program to check if the given array
# contains a palindromic pair of strings
# Trie node
class TrieNode:
def __init__(self):
# pointer array for 26 letters
self.children = [None] * 26
# indices of palindromic words
self.indices = []
# index of word in array
self.idx = -1
# Function to check if a string is palindrome
def isPalindrome(word, i, j):
# compare each character from starting
# with its corresponding character from last
while i < j:
if word[i] != word[j]:
return False
i += 1
j -= 1
return True
# If not present, inserts reverse of word into Trie.
# If the word is prefix of a Trie node, just mark leaf node
def insert(root, word, idx):
node = root
# Start traversing word from the last
for i in range(len(word) - 1, -1, -1):
# If current word is palindrome till this
# i, store index of current word.
if isPalindrome(word, 0, i):
node.indices.append(idx)
index = ord(word[i]) - ord('a')
if not node.children[index]:
node.children[index] = TrieNode()
node = node.children[index]
node.idx = idx
node.indices.append(idx)
# Returns true if word presents in Trie, else false
def search(root, word, idx):
node = root
for i in range(len(word)):
index = ord(word[i]) - ord('a')
# If it is present also check up to
# which index it is palindrome
if node.idx >= 0 and node.idx != idx and \
isPalindrome(word, i, len(word) - 1):
return True
if not node.children[index]:
return False
node = node.children[index]
return any(i != idx for i in node.indices)
# Function to check if a palindrome pair exists
def palindromePair(arr):
root = TrieNode()
# Construct trie
for i in range(len(arr)):
insert(root, arr[i], i)
# Search for different keys
for i in range(len(arr)):
if search(root, arr[i], i):
return True
return False
if __name__ == "__main__":
arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"]
if palindromePair(arr):
print("True")
else:
print("False")
C#
// C# program to check if the given array
// contains a palindromic pair of strings
using System;
using System.Collections.Generic;
class TrieNode {
// pointer array for 26 letters
public TrieNode[] children;
// indices of palindromic words
public List<int> indices;
// index of word in array
public int idx;
public TrieNode() {
// initialize children array to null
children = new TrieNode[26];
indices = new List<int>();
idx = -1;
}
}
class GFG {
// Function to check if a string is palindrome
static bool isPalindrome(string word, int i, int j) {
// compare each character from starting
// with its corresponding character from last
while (i < j) {
if (word[i] != word[j])
return false;
i++; j--;
}
return true;
}
// If not present, inserts reverse of word into Trie.
// If the word is prefix of a Trie node, just mark leaf node
static void insert(TrieNode root, string word, int idx) {
TrieNode node = root;
// Start traversing word from the last
for (int i = word.Length - 1; i >= 0; i--) {
// If current word is palindrome till this
// i, store index of current word.
if (isPalindrome(word, 0, i))
node.indices.Add(idx);
// If it is not available in Trie
// then store it
int index = word[i] - 'a';
if (node.children[index] == null)
node.children[index] = new TrieNode();
// move to new TrieNode
node = node.children[index];
}
node.idx = idx;
node.indices.Add(idx);
}
// Returns true if word presents in Trie, else false
static bool search(TrieNode root, string word, int idx) {
TrieNode node = root;
for (int i = 0; i < word.Length && node != null; i++) {
int index = word[i] - 'a';
// If it is present also check up to
// which index it is palindrome
if (node.idx >= 0 && node.idx != idx &&
isPalindrome(word, i, word.Length - 1))
return true;
node = node.children[index];
}
if (node != null) {
foreach (int i in node.indices) {
if (idx != i)
return true;
}
}
return false;
}
// Function to check if a palindrome pair exists
static bool palindromePair(string[] arr) {
// Construct trie
TrieNode root = new TrieNode();
for (int i = 0; i < arr.Length; i++)
insert(root, arr[i], i);
// Search for different keys
for (int i = 0; i < arr.Length; i++) {
if (search(root, arr[i], i))
return true;
}
return false;
}
static void Main() {
string[] arr = { "geekf", "geeks", "or", "keeg", "abc", "bc" };
if (palindromePair(arr))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to check if the given array
// contains a palindromic pair of strings
class TrieNode {
constructor() {
// pointer array for 26 letters
this.children = new Array(26).fill(null);
// indices of palindromic words
this.indices = [];
// index of word in array
this.idx = -1;
}
}
// Function to check if a string is palindrome
function isPalindrome(word, i, j) {
// compare each character from starting
// with its corresponding character from last
while (i < j) {
if (word[i] !== word[j])
return false;
i++; j--;
}
return true;
}
// If not present, inserts reverse of word into Trie.
// If the word is prefix of a Trie node, just mark leaf node
function insert(root, word, idx) {
let node = root;
// Start traversing word from the last
for (let i = word.length - 1; i >= 0; i--) {
// If current word is palindrome till this
// i, store index of current word.
if (isPalindrome(word, 0, i))
node.indices.push(idx);
// If it is not available in Trie
// then store it
let index = word.charCodeAt(i) - 'a'.charCodeAt(0);
if (!node.children[index])
node.children[index] = new TrieNode();
// move to new TrieNode
node = node.children[index];
}
node.idx = idx;
node.indices.push(idx);
}
// Returns true if word presents in Trie, else false
function search(root, word, idx) {
let node = root;
for (let i = 0; i < word.length && node; i++) {
let index = word.charCodeAt(i) - 'a'.charCodeAt(0);
// If it is present also check upto
// which index it is palindrome
if (node.idx >= 0 && node.idx !== idx &&
isPalindrome(word, i, word.length - 1))
return true;
node = node.children[index];
}
if (node) {
for (let i of node.indices) {
if (idx !== i)
return true;
}
}
return false;
}
// Function to check if a palindrome pair exists
function palindromePair(arr) {
// Construct trie
let root = new TrieNode();
for (let i = 0; i < arr.length; i++)
insert(root, arr[i], i);
// Search for different keys
for (let i = 0; i < arr.length; i++) {
if (search(root, arr[i], i))
return true;
}
return false;
}
// Driver code
let arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"];
if (palindromePair(arr))
console.log("True");
else
console.log("False");
Time Complexity: O(n * k2), here n is the number of strings in arr[] and k is the length of the longest string. For each string, we are checking if the substring arr[i][0..ind] is a palindrome (0 <= ind <= k), that takes (n * k * k) time.
Auxiliary Space: O(n * k), to store all the strings in the Trie.
[Alternate Approach] Using HashMap
The above approach can also be implemented using HashMap instead of Trie.
C++
// C++ program to check if the given array
// contains a plaindromic pair of strings
#include <bits/stdc++.h>
using namespace std;
// Function to check if a string is palindrome
bool isPalindrome(string &s) {
int n = s.length();
// compare each character from starting
// with its corresponding character from last
for (int i = 0; i < n/2; i++ )
if (s[i] != s[n-i-1])
return false;
return true;
}
// Function to check if a palindrome pair exists
bool palindromePair(vector<string> &arr) {
// to store all substrings of all words
// along with indices in reverse order
unordered_map<string, int> str;
// to store all reverse of all words
for (int i = 0; i < arr.size(); i++) {
string word = arr[i];
reverse(word.begin(), word.end());
str[word] = i;
}
// enumerating over all words and
// for each character of them
for (int i = 0; i < arr.size(); i++) {
// to store the left substring of arr[i]
string left = "";
for (int j = 0; j < arr[i].size(); j++) {
// add currrent character to word
left += arr[i][j];
// extract right substring
string right = arr[i].substr(j+1);
// if word is not empty and is palindrome
// and right is present in the map
if(!left.empty() && isPalindrome(left) && str.count(right) && str[right] != i)
return true;
// check the same by swapping word and right
if(isPalindrome(right) && str.count(left) && str[left] != i)
return true;
}
}
return false;
}
int main() {
vector<string> arr = {"geekf", "geeks", "or", "keeg", "abc", "bc"};
if (palindromePair(arr))
cout << "True";
else
cout << "False";
return 0;
}
Java
// Java program to check if the given array
// contains a palindromic pair of strings
import java.util.*;
class GFG {
// Function to check if a string is palindrome
static boolean isPalindrome(String s) {
int n = s.length();
// compare each character from starting
// with its corresponding character from last
for (int i = 0; i < n / 2; i++)
if (s.charAt(i) != s.charAt(n - i - 1))
return false;
return true;
}
// Function to check if a palindrome pair exists
static boolean palindromePair(String[] arr) {
// to store all substrings of all words
// along with indices in reverse order
Map<String, Integer> str = new HashMap<>();
// to store all reverse of all words
for (int i = 0; i < arr.length; i++) {
String word = new StringBuilder(arr[i]).reverse().toString();
str.put(word, i);
}
// enumerating over all words and
// for each character of them
for (int i = 0; i < arr.length; i++) {
// to store the left substring of arr[i]
String left = "";
for (int j = 0; j < arr[i].length(); j++) {
// add current character to word
left += arr[i].charAt(j);
// extract right substring
String right = arr[i].substring(j + 1);
// if word is not empty and is palindrome
// and right is present in the map
if (!left.isEmpty() && isPalindrome(left)
&& str.containsKey(right) && str.get(right) != i)
return true;
// check the same by swapping word and right
if (isPalindrome(right) && str.containsKey(left)
&& str.get(left) != i)
return true;
}
}
return false;
}
public static void main(String[] args) {
String[] arr = {"geekf", "geeks", "or", "keeg", "abc", "bc"};
if (palindromePair(arr))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python program to check if the given array
# contains a palindromic pair of strings
# Function to check if a string is palindrome
def isPalindrome(s):
n = len(s)
# compare each character from starting
# with its corresponding character from last
for i in range(n // 2):
if s[i] != s[n - i - 1]:
return False
return True
# Function to check if a palindrome pair exists
def palindromePair(arr):
# to store all substrings of all words
# along with indices in reverse order
strMap = {}
# to store all reverse of all words
for i in range(len(arr)):
word = arr[i][::-1]
strMap[word] = i
# enumerating over all words and
# for each character of them
for i in range(len(arr)):
# to store the left substring of arr[i]
left = ""
for j in range(len(arr[i])):
# add current character to word
left += arr[i][j]
# extract right substring
right = arr[i][j + 1:]
# if word is not empty and is palindrome
# and right is present in the map
if left and isPalindrome(left) and \
right in strMap and strMap[right] != i:
return True
# check the same by swapping word and right
if isPalindrome(right) and \
left in strMap and strMap[left] != i:
return True
return False
if __name__ == "__main__":
arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"]
if palindromePair(arr):
print("True")
else:
print("False")
C#
// C# program to check if the given array
// contains a palindromic pair of strings
using System;
using System.Collections.Generic;
class GFG {
// Function to check if a string is palindrome
static bool isPalindrome(string s) {
int n = s.Length;
// compare each character from starting
// with its corresponding character from last
for (int i = 0; i < n / 2; i++)
if (s[i] != s[n - i - 1])
return false;
return true;
}
// Function to check if a palindrome pair exists
static bool palindromePair(string[] arr) {
// to store all substrings of all words
// along with indices in reverse order
Dictionary<string, int> str = new Dictionary<string, int>();
// to store all reverse of all words
for (int i = 0; i < arr.Length; i++) {
char[] wordArr = arr[i].ToCharArray();
Array.Reverse(wordArr);
string word = new string(wordArr);
str[word] = i;
}
// enumerating over all words and
// for each character of them
for (int i = 0; i < arr.Length; i++) {
// to store the left substring of arr[i]
string left = "";
for (int j = 0; j < arr[i].Length; j++) {
// add current character to word
left += arr[i][j];
// extract right substring
string right = arr[i].Substring(j + 1);
// if word is not empty and is palindrome
// and right is present in the map
if (!string.IsNullOrEmpty(left) && isPalindrome(left)
&& str.ContainsKey(right) && str[right] != i)
return true;
// check the same by swapping word and right
if (isPalindrome(right) && str.ContainsKey(left)
&& str[left] != i)
return true;
}
}
return false;
}
public static void Main() {
string[] arr = { "geekf", "geeks", "or", "keeg", "abc", "bc" };
if (palindromePair(arr))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to check if the given array
// contains a palindromic pair of strings
// Function to check if a string is palindrome
function isPalindrome(s) {
let n = s.length;
// compare each character from starting
// with its corresponding character from last
for (let i = 0; i < Math.floor(n / 2); i++)
if (s[i] !== s[n - i - 1])
return false;
return true;
}
// Function to check if a palindrome pair exists
function palindromePair(arr) {
// to store all substrings of all words
// along with indices in reverse order
let str = new Map();
// to store all reverse of all words
for (let i = 0; i < arr.length; i++) {
let word = arr[i].split("").reverse().join("");
str.set(word, i);
}
// enumerating over all words and
// for each character of them
for (let i = 0; i < arr.length; i++) {
// to store the left substring of arr[i]
let left = "";
for (let j = 0; j < arr[i].length; j++) {
// add current character to word
left += arr[i][j];
// extract right substring
let right = arr[i].substring(j + 1);
// check palindrome conditions
if (left && isPalindrome(left) && str.has(right)
&& str.get(right) !== i)
return true;
if (isPalindrome(right) && str.has(left)
&& str.get(left) !== i)
return true;
}
}
return false;
}
// Driver code
let arr = ["geekf", "geeks", "or", "keeg", "abc", "bc"];
console.log(palindromePair(arr) ? "True" : "False");
Time Complexity: O(n * k2), here n is the number of strings in arr[] and k is the length of the longest string. For each string, we are checking if the substring arr[i][0..ind] is a palindrome (0 <= ind <= k), that takes (n * k * k) time.
Auxiliary Space: O(n * k), to store all the strings in the HashMap.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem