Largest word in dictionary by deleting some characters of given string
Last Updated :
24 Mar, 2025
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" .
[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));
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));
Time Complexity: O(n*k) Here n is the length of dictionary and k is the average word length in the dictionary.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read