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
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Remove the first and last character of each word in a string
Next article icon

Largest word in dictionary by deleting some characters of given string

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Giving a dictionary and a string ‘str’, find the longest string in dictionary which can be formed by deleting some characters of the given ‘str’. 

Examples: 

Input: dict = [ “ale”, “apple”, “monkey”, “plea” ], str =”abpcplea”
Output: apple
Explanation: On removing characters at indexes 1,3,7 we can form string “apple” , similarly we can form strings “ale” and “plea” also, but “apple” is the longest string so we return “apple”.

Input: dict = [ “pintu”, “geeksfor”, “geeksgeeks”, ” forgeek” ], str =”geeksforgeeks”
Output: geeksgeeks
Explanation: On removing characters at indexes 5,6,7 we can form string “geeksgeeks” , similarly we can form strings “geeksfor” and “forgeeks” also, but “geeksgeeks” is the longest string so we return “geeksgeeks” .

Table of Content

  • [Naive Approach] Using Sorting and Nested Loop – O(n^2logn) Time and O(1) Space
  • [Expected Approach] Using Nested Loop – O(n^2) Time and O(1) Space

[Naive Approach] Using Sorting and Nested Loop – O(n^2logn) Time and O(1) Space

A naive solution is we Sort the dictionary word. We traverse all dictionary words and for every word, we check if it is subsequence of given string and at last we check this subsequence  is largest of all such subsequence.. We finally return the longest word with given string as subsequence.

C++
#include <bits/stdc++.h> using namespace std;  bool isSubSequence(string d, string s){     int i = 0, j = 0;     while (i < d.size() && j < s.size()) {         if (d[i] == s[j]) {             i++;         }         j++;     }     return i == d.size();  }  string LongestWord(vector<string> d, string S) {     string res = "";            sort(d.begin(), d.end());     for (string word : d) {                  // If the word is a subsequence and longer than          // current result         if (isSubSequence(word, S) && word.size() > res.size()) {             res = word;           }     }          return res;       }  int main(){     vector<string> dict = { "ale", "apple", "monkey", "plea" };     string str = "abpcplea";     cout << LongestWord(dict, str) << endl;      return 0; } 
C
#include <stdio.h> #include <string.h>  int isSubSequence(char* str1, char* str2){     int m = strlen(str1);     int n = strlen(str2);      int j = 0;       for (int i = 0; i < n && j < m; i++)         if (str1[j] == str2[i])             j++;     return (j == m); }  char* LongestWord(char** dict, int n, char* str){     char* result = "";     int length = 0;     for (int k = 0; k < n; k++) {         char* word = dict[k];          // If current word is subsequence of str and is         // largest such word so far.         if (length < strlen(word)             && isSubSequence(word, str)) {             result = word;             length = strlen(word);         }     }     return result; } int main(){     char* dict[] = { "ale", "apple", "monkey", "plea" };     int n = sizeof(dict) / sizeof(dict[0]);     char str[] = "abpcplea";     printf("%s\n", LongestWord(dict, n, str));     return 0; } 
Java
import java.util.*;  public class Main {     public static boolean isSubSequence(String d, String s) {         int i = 0, j = 0;         while (i < d.length() && j < s.length()) {             if (d.charAt(i) == s.charAt(j)) {                 i++;             }             j++;         }         return i == d.length();       }      public static String LongestWord(List<String> d, String S) {         String res = "";          Collections.sort(d);         for (String word : d) {                          // If the word is a subsequence and longer than current result             if (isSubSequence(word, S) && word.length() > res.length()) {                 res = word;               }         }          return res;       }      public static void main(String[] args) {         List<String> dict = Arrays.asList("ale", "apple", "monkey", "plea");         String str = "abpcplea";         System.out.println(LongestWord(dict, str));       } } 
Python
def isSubSequence(d, s):     i, j = 0, 0     while i < len(d) and j < len(s):         if d[i] == s[j]:             i += 1         j += 1     return i == len(d)    def LongestWord(d, s):     res = ""       d.sort()     for word in d:                  # If the word is a subsequence         # and longer than current result         if isSubSequence(word, s) and len(word) > len(res):             res = word        return res    d = ["ale", "apple", "monkey", "plea"] s = "abpcplea" print(LongestWord(dict, str))  
C#
using System; using System.Linq; using System.Collections.Generic;  class Program {      public static bool IsSubSequence(string d, string s) {         int i = 0, j = 0;         while (i < d.Length && j < s.Length) {             if (d[i] == s[j]) {                 i++;             }             j++;         }         return i == d.Length;       }         public static string LongestWord(List<string> d, string S) {         string res = "";           d.Sort();         foreach (string word in d) {             // If the word is a subsequence and longer than current result             if (IsSubSequence(word, S) && word.Length > res.Length) {                 res = word;               }         }          return res;      }      static void Main() {         List<string> dict = new List<string> { "ale", "apple", "monkey", "plea" };         string str = "abpcplea";         Console.WriteLine(LongestWord(dict, str));       } } 
JavaScript
function isSubSequence(d, s) {     let i = 0, j = 0;     while (i < d.length && j < s.length) {         if (d[i] === s[j]) {             i++;         }         j++;     }     return i === d.length;   }  function LongestWord(d, s) {     let res = "";      d.sort();      for (let word of d) {                  // If the word is a subsequence and longer          // than current result         if (isSubSequence(word, s) && word.length > res.length) {             res = word;          }     }      return res;   }  let d = ["ale", "apple", "monkey", "plea"]; let s = "abpcplea"; console.log(LongestWord(dict, str));  

Output
apple 

Time Complexity: O((n*k) +(n*(klogk))). Here n is the length of dictionary and k is the average word length in the dictionary. n*k for checking if a string is subsequence of str in the dict and nklogk for sorting each word in the dict.

[Expected Approach] Using Nested Loop – O(n^2) Time and O(1) Space

This problem reduces to finding if a string is subsequence of another string or not. We traverse all dictionary words and for every word, we check if it is subsequence of given string and is largest of all such words. We finally return the longest word with given string as subsequence.
C++
#include <bits/stdc++.h> using namespace std;  bool isSubSequence(string s1, string s2){     int m = s1.size(), n = s2.size();      int j = 0;       for (int i = 0; i < n && j < m; i++)         if (s1[j] == s2[i])             j++;     return (j == m); }  string LongestWord(vector<string> dict, string str){     string result = "";     int length = 0;     for (string word : dict) {                  // If current word is subsequence of str and is         // largest such word so far.         if (length < word.length()             && isSubSequence(word, str)) {             result = word;             length = word.length();         }     }      return result; } int main() {     vector<string> dict= { "pintu", "geeksfor", "geeksgeeks", "forgeek" };     string str = "geeksforgeeks";     cout << LongestWord(dict, str) << endl;     return 0; } 
C
#include <stdio.h> #include <string.h>   int isSubSequence(char* s, char* s2) {     int m = strlen(str1), n = strlen(str2);     int j = 0;       for (int i = 0; i < n && j < m; i++) {         if (s1[j] == s2[i]) {             j++;         }     }     return (j == m); } char* LongestWord(char* dict[], int dictSize, char* str) {     char* result = "";     int length = 0;     for (int i = 0; i < dictSize; i++) {         char* word = dict[i];          // If current word is subsequence of str and is largest such word so far         if (length < strlen(word) && isSubSequence(word, str)) {             result = word;             length = strlen(word);         }     }     return result; } int main() {     char* dict[] = { "pintu", "geeksfor", "geeksgeeks", "forgeek" };     char str[] = "geeksforgeeks";     printf("%s\n", LongestWord(dict, 4, str));       return 0; } 
Java
import java.util.*;  public class GFG {     public static boolean isSubSequence(String s1, String s2) {         int m = s1.length(), n = s2.length();         int j = 0;           for (int i = 0; i < n && j < m; i++) {             if (s1.charAt(j) == s2.charAt(i)) {                 j++;               }         }         return j == m;      }      public static String LongestWord(List<String> dict, String str) {         String result = "";           int length = 0;         for (String word : dict) {             // Check if word is subsequence and longer than current result             if (length < word.length() && isSubSequence(word, str)) {                 result = word;                 length = word.length();             }         }         return result;      }      public static void main(String[] args) {         List<String> dict = Arrays.asList("pintu", "geeksfor", "geeksgeeks", "forgeek");         String str = "geeksforgeeks";         System.out.println(LongestWord(dict, str));       } } 
Python
def isSubSequence(s1, s2):     m, n = len(s1), len(s2)     j = 0             for i in range(n):         if s1[j] == s2[i]:             j += 1           if j == m:             break     return j == m   def LongestWord(dict, str):     result = ""       length = 0           for word in dict:         # Check if word is subsequence and longer than current result         if length < len(word) and isSubSequence(word, str):             result = word             length = len(word)      return result    # Driver code dict = ["pintu", "geeksfor", "geeksgeeks", "forgeek"] str = "geeksforgeeks" print(LongestWord(dict, str)) 
C#
using System; using System.Linq; using System.Collections.Generic;  class Program {      public static bool IsSubSequence(string s1, string s2) {         int m = s1.Length, n = s2.Length;         int j = 0;                    for (int i = 0; i < n && j < m; i++) {             if (s1[j] == s2[i]) {                 j++;               }         }         return j == m;       }          public static string LongestWord(List<string> dict, string str) {         string result = "";          int length = 0;                  foreach (string word in dict) {             // Check if word is subsequence and longer than current result             if (length < word.Length && IsSubSequence(word, str)) {                 result = word;                 length = word.Length;             }         }          return result;       }      static void Main() {         List<string> dict = new List<string> { "pintu", "geeksfor", "geeksgeeks", "forgeek" };         string str = "geeksforgeeks";         Console.WriteLine(LongestWord(dict, str));      } } 
JavaScript
function isSubSequence(s1, s2) {     let m = s1.length, n = s2.length;     let j = 0;       for (let i = 0; i < n; i++) {         if (s1[j] === s2[i]) {             j++;  /         }     }     return j === m;  }  function LongestWord(dict, str) {     let result = "";       let length = 0;           for (let word of dict) {         // Check if word is subsequence and longer than current result         if (length < word.length && isSubSequence(word, str)) {             result = word;             length = word.length;         }     }      return result;   } let dict = ["pintu", "geeksfor", "geeksgeeks", "forgeek"]; let str = "geeksforgeeks"; console.log(LongestWord(dict, str));   

Output
apple 

Time Complexity: O(n*k) Here n is the length of dictionary and k is the average word length in the dictionary.



Next Article
Remove the first and last character of each word in a string

N

Nishant Singh
Improve
Article Tags :
  • DSA
  • Strings
  • subsequence
Practice Tags :
  • Strings

Similar Reads

  • Largest string obtained in Dictionary order after deleting K characters
    Given string str of length N and an integer K, the task is to return the largest string in Dictionary Order by erasing K characters from that string. A largest string Dictionary order is the last string when strings are arranged in alphabetical order. Examples: Input: str = "ritz" K = 2Output: tzExp
    6 min read
  • Python Dictionary to find mirror characters in a string
    Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end.
    2 min read
  • Generate longest String with character sum at most K by deleting letters
    Given a string str and an integer K, the task is to find the longest string that can be made by deleting letters from the given string such that the sum of the characters of the remaining string is at most K. Note: The value of the string is calculated as the sum of the value of characters (a value
    7 min read
  • Remove the first and last character of each word in a string
    Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if
    4 min read
  • Maximize characters to be removed from string with given condition
    Given a string s. The task is to maximize the removal of characters from s. Any character can be removed if at least one of its adjacent characters is the previous letter in the Latin English alphabet. Examples: Input: s = "bacabcab"Output: 4Explanation: Following are the removals that maximize the
    6 min read
  • Sum of indices of Characters removed to obtain an Empty String based on given conditions
    Given a string str, consisting of lowercase English alphabets, the task is to calculate the sum of indices(1-based indexing) of the characters removed to obtain an empty string by the following operations: Remove the smallest alphabet in the string.For multiple occurrences of the smallest alphabet,
    13 min read
  • Largest possible number by deleting given digit
    Find the largest positive integer that can be formed by deleting only one occurrence of a given digit. Examples: Input: num = 56321, digit = 5Output: 6321Explanation: Since the number 56321 contain only 1 occurrence of 5, we can remove it to get 6321 which is the largest possible positive number. In
    7 min read
  • Remove odd indexed characters from a given string
    Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string. Examples : Input: str = “abcdef”Output: aceExplanation:The characters 'b', 'd' and 'f' are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed f
    4 min read
  • Maximize minority character deletions that can be done from given Binary String substring
    Python Given binary string str of size, N. Select any substring from the string and remove all the occurrences of the minority character (i.e. the character having less frequency) from the substring. The task is to find out the maximum number of characters that can be removed from performing one suc
    5 min read
  • Lexicographically largest string formed in minimum moves by replacing characters of given String
    Given a string S consisting of N lowercase English characters, the task is to print the lexicographically, the largest string obtained using only the minimum number of moves needed to modify the string S to a string containing the first min(N, 26) lower case English alphabet, by replacing any charac
    10 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