Check if Prefix String exists in the Array

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Output
Yes

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

Output
Yes

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)


Next Article
Article Tags :
Practice Tags :

Similar Reads