Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count of strings whose prefix match with the given string to a given length k
Next article icon

Longest string in an array which matches with prefix of the given string

Last Updated : 06 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of strings arr[] and Q queries where each query consists of a string str, the task is to find the longest string in the array that matches with prefix of the given string str i.e. the string must be prefix of str. 
Examples:

Input: arr[] = {“GeeksForGeeks”, “GeeksForGeeksd”, “Arnab”, “Art”}, q[] = {“GeeksForGeeks”, “Ar”, “Art”} 
Output: GeeksForGeeks -1 Art 
Input: arr[] = {“Geek”, “Geek”, “Geekss”, “Geekk”}, q[] = {“Geek”, “Geeks”, “Geekk”, “Gee”} 
Output: Geek -1 Geekk -1

Naive approach: For every given string traverse through the array and check for the string which matches with prefix of the given string and store and print the longest string. Efficient Approach: This problem can be solved using a Trie. We will form an trie and insert the strings of the array in the trie and find the longest string that completely matches with the prefix of the given string. Below is the implementation of the above approach: 

CPP




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
const int ALPHABET_SIZE = 26;
 
// Trie node
struct TrieNode {
    struct TrieNode* children[ALPHABET_SIZE];
 
    // isEndOfWord is true if the node represents
    // end of a word
    bool isEndOfWord;
};
 
// Returns new trie node (initialized to NULLs)
struct TrieNode* getNode(void)
{
    struct TrieNode* pNode = new TrieNode;
 
    pNode->isEndOfWord = false;
 
    for (int i = 0; i < ALPHABET_SIZE; i++)
        pNode->children[i] = NULL;
 
    return pNode;
}
 
// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
void insert(struct TrieNode* root, string key)
{
    struct TrieNode* pCrawl = root;
 
    for (int i = 0; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();
 
        if (i == key.length() - 1)
 
            // Mark last node as leaf
            pCrawl->children[index]->isEndOfWord = true;
 
        pCrawl = pCrawl->children[index];
    }
}
 
string getString(char x)
{
    // string class has a constructor
    // that allows us to specify size of
    // string as first parameter and character
    // to be filled in given size as second
    // parameter.
    string s(1, x);
 
    return s;
}
 
// Function to return the
// longest required string
string search(struct TrieNode* root, string key)
{
    struct TrieNode* pCrawl = root;
 
    // Prefix of the string
    string s = "";
 
    for (int i = 0; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!pCrawl->children[index])
            break;
 
        s += getString((char)key[i]);
 
        pCrawl = pCrawl->children[index];
    }
 
    if (pCrawl->isEndOfWord)
        return s;
 
    return "-1";
}
 
// Driver code
int main()
{
    string arr[] = { "Geeks", "Geek",
                    "Geekss", "Geekks" };
    int n = sizeof(arr) / sizeof(string);
 
    // Construct trie
    struct TrieNode* root = getNode();
    for (int i = 0; i < n; i++)
        insert(root, arr[i]);
 
    string queries[] = { "Geek", "Geeks", "Geekk", "Gee" };
    int q = sizeof(queries) / sizeof(string);
 
    for (int i = 0; i < q; i++)
        cout << search(root, queries[i]) << endl;
 
    return 0;
}
 
 

Java




import java.util.ArrayList;
// Trie node
class TrieNode {
    TrieNode[] children = new TrieNode[26];
      // isEndOfWord is true if the node represents
    // end of a word
    boolean isEndOfWord;
     
    TrieNode() {
        isEndOfWord = false;
        for (int i = 0; i < 26; i++)
            children[i] = null;
    }
}
 
public class Trie {
    TrieNode root;
   
    Trie() {
        root = new TrieNode();
    }
    // If not present, inserts key into trie
    // If the key is prefix of trie node, just
    // marks leaf node
    void insert(String key) {
        int n = key.length();
        TrieNode pCrawl = root;
 
        for (int i = 0; i < n; i++) {
            int index = key.charAt(i) - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
            pCrawl = pCrawl.children[index];
        }
       //Making True because we have reached to end
        pCrawl.isEndOfWord = true;
    }
    // Function to return the
    // longest required string
    String search(String key) {
        int n = key.length();
        TrieNode pCrawl = root;
        StringBuilder s = new StringBuilder();
 
        for (int i = 0; i < n; i++) {
            int index = key.charAt(i) - 'a';
            if (pCrawl.children[index] == null)
                break;
            s.append(key.charAt(i));
            pCrawl = pCrawl.children[index];
        }
        if (pCrawl != null && pCrawl.isEndOfWord)
            return s.toString();
        return "-1";
    }
 
    public static void main(String[] args) {
        Trie trie = new Trie();
 
        String[] arr = { "geeks", "geek", "geekss", "geekks" };
        int n = arr.length;
        // Inserting every string into trie
        for (int i = 0; i < n; i++)
            trie.insert(arr[i]);
        String[] queries = { "geek", "geeks", "geekk", "gee" };
        int q = queries.length;
 
        for (int i = 0; i < q; i++)
            System.out.println(trie.search(queries[i]));
    }
}
 
 

Python3




# Python implementation of the approach
 
# Trie node
class TrieNode:
    def __init__(self):
        self.children = [None] * 26
         
        # isEndOfWord is true if the node represents
        # end of a word
        self.is_end_of_word = False
 
# Returns new trie node (initialized to None)
def get_node():
    node = TrieNode()
    return node
 
# If not present, inserts key into trie
# If the key is prefix of trie node, just
# marks leaf node
def insert(root, key):
    crawl = root
    for i in range(len(key)):
        index = ord(key[i]) - ord('a')
        if not crawl.children[index]:
            crawl.children[index] = get_node()
        if i == len(key) - 1:
            crawl.children[index].is_end_of_word = True
        crawl = crawl.children[index]
 
# Function to return the
# longest required string
def search(root, key):
    crawl = root
    # Prefix of the string
    s = ""
    for i in range(len(key)):
        index = ord(key[i]) - ord('a')
        if not crawl.children[index]:
            break
        s += key[i]
        crawl = crawl.children[index]
    if crawl and crawl.is_end_of_word:
        return s
    return "-1"
 
# Driver code
def main():
    arr = ["Geeks", "Geek", "Geekss", "Geekks"]
    n = len(arr)
 
    # Construct trie
    root = get_node()
    for i in range(n):
        insert(root, arr[i])
 
    queries = ["Geek", "Geeks", "Geekk", "Gee"]
    q = len(queries)
 
    for i in range(q):
        print(search(root, queries[i]))
 
if __name__ == "__main__":
    main()
 
# This code is contributed by Aman Kumar.
 
 

C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
// Trie node
class TrieNode {
  public TrieNode[] children = new TrieNode[26];
 
  // isEndOfWord is true if the node represents
  // end of a word
  public bool isEndOfWord;
  public TrieNode() {
    isEndOfWord = false;
    for (int i = 0; i < 26; i++)
      children[i] = null;
  }
}
 
public class Trie {
  private TrieNode root;
  public Trie() {
    root = new TrieNode();
  }
 
  // If not present, inserts key into trie
  // If the key is prefix of trie node, just
  // marks leaf node
  public void Insert(string key) {
    int n = key.Length;
    TrieNode pCrawl = root;
 
    for (int i = 0; i < n; i++) {
      int index = key[i] - 'a';
      if (pCrawl.children[index] == null)
        pCrawl.children[index] = new TrieNode();
      pCrawl = pCrawl.children[index];
    }
    //Making True because we have reached to end
    pCrawl.isEndOfWord = true;
  }
  // Function to return the
  // longest required string
  public string Search(string key) {
    int n = key.Length;
    TrieNode pCrawl = root;
    System.Text.StringBuilder s = new System.Text.StringBuilder();
 
    for (int i = 0; i < n; i++) {
      int index = key[i] - 'a';
      if (pCrawl.children[index] == null)
        break;
      s.Append(key[i]);
      pCrawl = pCrawl.children[index];
    }
    if (pCrawl != null && pCrawl.isEndOfWord)
      return s.ToString();
    return "-1";
  }
 
  public static void Main(string[] args) {
    Trie trie = new Trie();
 
    string[] arr = { "geeks", "geek", "geekss", "geekks" };
    int n = arr.Length;
 
    // Inserting every string into trie
    for (int i = 0; i < n; i++)
      trie.Insert(arr[i]);
    string[] queries = { "geek", "geeks", "geekk", "gee" };
    int q = queries.Length;
 
    for (int i = 0; i < q; i++)
      Console.WriteLine(trie.Search(queries[i]));
  }
}
 
// this code is contributed by bhardwajji
 
 

Javascript




// Trie node
class TrieNode {
constructor() {
this.children = Array(26).fill(null);
// isEndOfWord is true if the node represents end of a word
this.is_end_of_word = false;
}
}
 
// Returns new trie node (initialized to null)
function get_node() {
const node = new TrieNode();
return node;
}
 
// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
function insert(root, key) {
let crawl = root;
for (let i = 0; i < key.length; i++) {
const index = key[i].charCodeAt(0) - 'a'.charCodeAt(0);
if (!crawl.children[index]) {
crawl.children[index] = get_node();
}
if (i === key.length - 1) {
crawl.children[index].is_end_of_word = true;
}
crawl = crawl.children[index];
}
}
 
// Function to return the longest required string
function search(root, key) {
let crawl = root;
// Prefix of the string
let s = "";
for (let i = 0; i < key.length; i++) {
const index = key[i].charCodeAt(0) - 'a'.charCodeAt(0);
if (!crawl.children[index]) {
break;
}
s += key[i];
crawl = crawl.children[index];
}
if (crawl && crawl.is_end_of_word) {
return s;
}
return "-1";
}
 
// Driver code
function main() {
const arr = ["Geeks", "Geek", "Geekss", "Geekks"];
const n = arr.length;
 
// Construct trie
const root = get_node();
for (let i = 0; i < n; i++) {
insert(root, arr[i]);
}
 
const queries = ["Geek", "Geeks", "Geekk", "Gee"];
const q = queries.length;
 
for (let i = 0; i < q; i++) {
console.log(search(root, queries[i]));
}
}
 
 
main();
 
 
Output:
Geek Geeks -1 -1


Next Article
Count of strings whose prefix match with the given string to a given length k
author
andrew1234
Improve
Article Tags :
  • Advanced Data Structure
  • Competitive Programming
  • DSA
  • Searching
  • Strings
  • prefix
  • Trie
Practice Tags :
  • Advanced Data Structure
  • Searching
  • Strings
  • Trie

Similar Reads

  • Count of strings whose prefix match with the given string to a given length k
    Given an array of strings arr[] and given some queries where each query consists of a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str.Examples: Input: arr[] = {"abba", "abbb", "abbc", "abbd", "abaa", "abc
    15+ min read
  • Find the Longest Non-Prefix-Suffix Substring in the Given String
    Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
    7 min read
  • Length of longest prefix anagram which are common in given two strings
    Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str
    8 min read
  • Find a string which matches all the patterns in the given array
    Given an array of strings arr[] which contains patterns of characters and "*" denoting any set of characters including the empty string. The task is to find a string that matches all the patterns in the array.Note: If there is no such possible pattern, print -1. Examples: Input: arr[] = {"pq*du*q",
    10 min read
  • Print the longest prefix of the given string which is also the suffix of the same string
    Given string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1. Examples: Input: str = "aabcdaabc" Output: aabc The string "aabc" is the longest prefix which is also suffix. Input
    8 min read
  • Longest string which is prefix string of at least two strings
    Given a set of strings of the same length, we need to find the length of the longest string, which is a prefix string of at least two strings. Examples: Input: ["abcde", "abcsd", "bcsdf", "abcda", "abced"] Output: 4 Explanation: Longest prefix string is "abcd". Input: ["pqrstq", "pwxyza", "abcdef",
    6 min read
  • Remove longest prefix of the String which has duplicate substring
    Given a string S of length N, the task is to remove the longest prefix of the string which has at least one duplicate substring present in S. Note: The duplicate substring cannot be the prefix itself Examples: Input: S = "GeeksforGeeks"Output: "forGeeks"Explanation: The longest substring which has a
    5 min read
  • Longest Common Substring in an Array of Strings
    We are given a list of words sharing a common stem i.e the words originate from same word for ex: the words sadness, sadly and sad all originate from the stem 'sad'. Our task is to find and return the Longest Common Substring also known as stem of those words. In case there are ties, we choose the s
    7 min read
  • Find the longest Substring of a given String S
    Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1. Examples: Input: S = "2347"Output: 3?Explanation:
    10 min read
  • 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences