Check if Prefix String exists in the Array
Last Updated :
27 May, 2024
Given an array of strings, the task is to print "Yes" if it contains a string that is a prefix of another string otherwise, print "No".
Examples:
Input: arr[] = {"rud", "rudra", "rahi"}
Output: Yes
Explanation: arr[0] = "rud" is a prefix of arr[1] = "rudra", that's why "Yes" is the output.
Input: arr[] = {"baj", "mnc", "rahi", "banjo"}
Output: No
Input: arr[] = {"bahe", "baj", "jabf", "bahej"}
Output: Yes
Approach: To solve the problem follow the below idea:
The approach basically requires us to match one string to another, such that checking whether one contains prefix of another, with the help of find method which returns the first position where there is a prefix match, and in case of prefix it would definitely be zero.
Steps to follow to implement the approach:
- The "hasPrefix" function takes an array of strings "arr" and its size "n" as input.
- It then iterates through each string in the array, and for each string, it checks if it is a prefix of any other string in the array using the "find" method of the "string" class. If it is, the function immediately returns "true".
- If no string is found to be a prefix of another string, the function returns "false".
- The main function creates an example string array, calls the "hasPrefix" function, and prints "Yes" if the function returns "true", and "No" otherwise.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach
#include <iostream>
#include <string>
using namespace std;
bool hasPrefix(string arr[], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Matching ith and jth strings
// whether one is prefix
// of another
if (i != j && arr[j].find(arr[i]) == 0) {
return true;
}
}
}
return false;
}
// Driver's code
int main()
{
string arr[] = { "rud", "rudra", "rahi" };
int n = sizeof(arr) / sizeof(arr[0]);
if (hasPrefix(arr, n)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
Java
// Java code for the same
import java.util.Arrays;
public class Main {
public static boolean hasPrefix(String[] arr)
{
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
// Matching ith and jth strings whether one is
// prefix of another
if (i != j && arr[j].indexOf(arr[i]) == 0) {
return true;
}
}
}
return false;
}
// Driver's code
public static void main(String[] args)
{
String[] arr = { "rud", "rudra", "rahi" };
if (hasPrefix(arr)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
Python
# Function to check if any string in the array is a prefix of another string
def has_prefix(arr):
for i in range(len(arr)):
for j in range(len(arr)):
# Check if the i-th and j-th strings are different and
# if the j-th string starts with the i-th string
if i != j and arr[j].startswith(arr[i]):
return True # Return True if a prefix is found
return False # Return False if no prefix is found
# Driver's code
arr = ["rud", "rudra", "rahi"]
if has_prefix(arr):
print("Yes") # Output "Yes" if a prefix is found
else:
print("No") # Output "No" if no prefix is found
#This code is contributed by rudra1807raj
C#
// C# code for the above implementation
using System;
public class MainClass {
public static bool HasPrefix(string[] arr)
{
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j < arr.Length; j++) {
// Matching ith and jth strings whether one is
// prefix of another
if (i != j && arr[j].IndexOf(arr[i]) == 0) {
return true;
}
}
}
return false;
}
// Driver's code
public static void Main()
{
string[] arr = { "rud", "rudra", "rahi" };
if (HasPrefix(arr)) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
}
JavaScript
// Function to check if any string in the array is a prefix of another string
function hasPrefix(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
// Matching ith and jth strings
// whether one is prefix
// of another
if (i !== j && arr[j].startsWith(arr[i])) {
return true; // Return true if a prefix is found
}
}
}
return false; // Return false if no prefix is found
}
// Driver's code
const arr = ["rud", "rudra", "rahi"];
if (hasPrefix(arr)) {
console.log("Yes"); // Output "Yes" if a prefix is found
} else {
console.log("No"); // Output "No" if no prefix is found
}
//This code is contributed by rudra1807raj
Time Complexity: O(n^2 * m), where n is the length of the input array and m is the maximum length of a string in the array. This is because the code uses nested loops to compare every pair of strings in the array, and for each pair, it uses the find method to check if one string is a prefix of the other. The find method has a time complexity of O(m).
Auxiliary Space: O(1), as it only uses a fixed amount of memory to store the input array and a few loop variables. The space used does not depend on the size of the input.
Using Trie Data Structure for Prefix String Existence Check
The approach involves utilizing a Trie data structure to efficiently determine if any string in the array is a prefix of another string.
Follow the steps to solve the above problem:
- Initializes a Trie node with an empty dictionary for children and a boolean to mark the end of a word.
- Inserts a word into the Trie character by character.
- If a character does not exist in the current node's children, it creates a new TrieNode for that character. At the end of the word, it sets the
is_end_of_word
flag to True
.
- Checks if any word in the array is a prefix of another word by first inserting all the words into a Trie. Then, traverse each word to check if it encounters a node that marks the end of another word (indicating a prefix).
- If such a node is found, it returns
True
. If no prefixes are found, it returns False
.
Below is the implementation of above approach:
C++
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
// TrieNode class to represent each node in the Trie
class TrieNode {
public:
std::unordered_map<char, TrieNode*> children;
bool isEndOfWord;
// Constructor to initialize a Trie node
TrieNode() : isEndOfWord(false) {}
};
// Function to insert a word into the Trie
void insert(TrieNode* root, const std::string& word) {
TrieNode* node = root;
for (char c : word) {
if (node->children.find(c) == node->children.end()) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->isEndOfWord = true;
}
// Function to check if any word in the array is a prefix of another word
bool hasPrefix(const std::vector<std::string>& arr) {
TrieNode* root = new TrieNode();
for (const std::string& word : arr) {
insert(root, word);
}
for (const std::string& word : arr) {
TrieNode* node = root;
for (char c : word) {
if (node->isEndOfWord) {
return true;
}
if (node->children.find(c) == node->children.end()) {
break;
}
node = node->children[c];
}
}
return false;
}
// Main function to test the hasPrefix function
int main() {
std::vector<std::string> arr = { "rud", "rudra", "rahi" };
if (hasPrefix(arr)) {
std::cout << "Yes" << std::endl; // Output "Yes" if a prefix is found
} else {
std::cout << "No" << std::endl; // Output "No" if no prefix is found
}
return 0;
}
// This code is contributed by Shivam
Java
import java.util.HashMap;
import java.util.Map;
class TrieNode {
Map<Character, TrieNode> children;
boolean isEndOfWord;
// Initialize a Trie node with an empty map for children
// and a boolean to mark end of a word
public TrieNode()
{
children = new HashMap<>();
isEndOfWord = false;
}
}
public class Trie {
// Function to insert a word into the Trie
public static void insert(TrieNode root, String word)
{
TrieNode node = root;
for (char c : word.toCharArray()) {
node.children.putIfAbsent(c, new TrieNode());
node = node.children.get(c);
}
node.isEndOfWord = true;
}
// Function to check if any word in the array is a
// prefix of another word
public static boolean hasPrefix(String[] arr)
{
TrieNode root = new TrieNode();
for (String word : arr) {
insert(root, word);
}
for (String word : arr) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.isEndOfWord) {
return true;
}
if (!node.children.containsKey(c)) {
break;
}
node = node.children.get(c);
}
}
return false;
}
public static void main(String[] args)
{
String[] arr = { "rud", "rudra", "rahi" };
if (hasPrefix(arr)) {
System.out.println(
"Yes"); // Output "Yes" if a prefix is found
}
else {
System.out.println(
"No"); // Output "No" if no prefix is found
}
}
}
Python
class TrieNode:
# Initialize a Trie node with an empty dictionary for children and
# a boolean to mark end of a word
def __init__(self):
self.children = {}
self.is_end_of_word = False
# Function to insert a word into the Trie
def insert(root, word):
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
# Function to check if any word in the array is a prefix of another word
def has_prefix(arr):
root = TrieNode()
for word in arr:
insert(root, word)
for word in arr:
node = root
for char in word:
if node.is_end_of_word:
return True
if char not in node.children:
break
node = node.children[char]
return False
# Driver's code
arr = ["rud", "rudra", "rahi"]
if has_prefix(arr):
print("Yes") # Output "Yes" if a prefix is found
else:
print("No") # Output "No" if no prefix is found
JavaScript
class TrieNode {
constructor() {
this.children = new Map();
this.isEndOfWord = false;
}
}
// Function to insert a word into the Trie
function insert(root, word) {
let node = root;
for (let c of word) {
if (!node.children.has(c)) {
node.children.set(c, new TrieNode());
}
node = node.children.get(c);
}
node.isEndOfWord = true;
}
// Function to check if any word in the array is a prefix of another word
function hasPrefix(arr) {
let root = new TrieNode();
for (let word of arr) {
insert(root, word);
}
for (let word of arr) {
let node = root;
for (let c of word) {
if (node.isEndOfWord) {
return true;
}
if (!node.children.has(c)) {
break;
}
node = node.children.get(c);
}
}
return false;
}
let arr = ["rud", "rudra", "rahi"];
if (hasPrefix(arr)) {
console.log("Yes"); // Output "Yes" if a prefix is found
} else {
console.log("No"); // Output "No" if no prefix is found
}
// This code is contributed by Shivam
Time Complexity: O(n * m), where n is the length of the input array and m is the maximum length of a string.
Auxilary Space: O(n * m)
Similar Reads
Check if given String is prefix subarray of the given Array
Given a string str and an array of words word[], the task is to find whether str is a prefix string of word[]. Examples: Input: str = "indiaismycountry", word[] = {"india", "is", "my", "country", "and", "i", "love", "india"}Output: trueExplanation: String str can be made by concatenating "india", "i
5 min read
Queries to check if string B exists as substring in string A
Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Exam
15+ min read
Check if given words are present in a string
Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : that you can
15+ min read
Check if two same sub-sequences exist in a string or not
Given a string, the task is to check if there exist two equal sub-sequences in the given string. Two sub-sequences are said to be equal if they have the same characters arranged in the same lexicographical order but the position of characters differs from that in the original string. Examples: Input
5 min read
Check if a string consists only of special characters
Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print âYesâ. Otherwise, print âNoâ. Examples: Input: str = â@#$&%!~âOutput: YesExplanation: Given string contains only special char
9 min read
Check if suffix and prefix of a string are palindromes
Given a string 's', the task is to check whether the string has both prefix and suffix substrings of length greater than 1 which are palindromes. Print 'YES' if the above condition is satisfied or 'NO' otherwise. Examples: Input : s = abartbb Output : YES Explanation : The string has prefix substrin
8 min read
Check if All Words Exist in a Sentence
Given a space separated strings sentence and an array of strings words[], the task is to determine if the sentence contains all the words from the array, returning true if all are present and false otherwise.Example:Input: sentence: "the quick brown fox jumps over the lazy dog", words: ["quick", "fo
9 min read
Number of strings in two array satisfy the given conditions
Given two arrays of string arr1[] and arr2[]. For each string in arr2[](say str2), the task is to count numbers string in arr1[](say str1) which satisfy the below conditions: The first characters of str1 and str2 must be equal.String str2 must contain each character of string str1.Examples: Input: a
14 min read
Check duplicates in a stream of strings
Given an array arr[] of strings containing the names of employees in a company. Assuming that the names are being entered into a system one after another, the task is to check whether the current name is entered for the first time or not. Examples: Input: arr[] = {"geeks", "for", "geeks"} Output: No
4 min read
Check if a string is substring of another
Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1.Examples : Input: txt = "geeksforgeeks", pat = "eks"Output: 2Explanation: String "eks" is present at index 2 and 9, so 2 is the smallest index.Input: txt
8 min read