Word Break

You are given a list of “N” strings A. Your task is to check whether you can form a given target string using a combination of one or more strings of A.

Note :
You can use any string of A multiple times.
Examples :
A =[“coding”, ”ninjas”, “is”, “awesome”]  target = “codingninjas”
Ans = true as we use “coding” and “ninjas” to form “codingninjas”
Input format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 
Then the T test cases follow.

The first line of each test contains a single integer N denoting the total number of strings in A.

The second line of each test contains “N” space-separated strings of A.

The third line of each test contains a single string target. 
Output format :
For each test case, print 1 if you can form a target string else print 0.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5 
1 <= N, | target | <= 10^2
1 <= | A[i] | <= 10

Where | A[i] | denotes length of string i,| target | denotes the length of the string target and A[i] contains only lowercase English characters.

Time limit: 1 sec
CodingNinjas
author
2y

One Sentence (string) is given. find out the words, that has length even and greater than equal to 4 (e.g. 4,6,8.. etc.) and separate them with space.
e.g. Given String : “abcd abc abcde abcdef”
Output...read more

CodingNinjas
author
2y
Brute Force

In this solution, we will try to generate all prefixes and If we want a prefix present in the string then we will recur for the remaining string.

Steps:

  1. Store all strings of A on the hash ma...read more
CodingNinjas
author
2y
Top down DP

In this solution, we will use the Overlapping Subproblems property. We will store the already calculated result in a dp array.

Here we will store the result of our recursion in a dp array. 

    We can implement the above approach by – 

  1. Store all strings of A on the hash map.
  2. Declare a function wordBreakHelper which will take three arguments: string, start, and dp array.
  3. If start equals the length of the string then return true.
  4. Run a loop from i = 1 to the length of the string.
  5. If dp[start] is already calculated then return it.
  6. If substring from 0 to i exists in the map and recursion of the remaining string gives true then return true.
  7. After running the loop, return false.
Space Complexity: O(n)Explanation:

O(N),  where N is the length of the string target.

 

We are storing all strings in a hashmap which will take O(N) space.

Hence the space complexity will be O(N).

Time Complexity: O(n^2)Explanation:

O(N^2), where N is the length of the string target.

 

In this case, we are generating and checking all subarrays of the target string which will take O(N) time.

Hence the overall complexity will be O(N^2). 


Python (3.5)
'''

Time Complexity: O(N ^ 2)
Space Compelxity: O(N)

Where N is the length of the target string.
'''

hashMap = dict()

def wordBreakHelper(s, start, dp):

# Base case.
if start == len(s):
dp[start] = 1
return dp[start]

# If the result is already calculated, then return it.
if dp[start] != -1:
return dp[start]

# Run a loop from 1 to length of the target string.
for i in range(start + 1, len(s) + 1, 1):
'''
If substring from 0 to i exist in hash map
and remaining string recurs true
'''
if s[start:i] in hashMap:
if wordBreakHelper(s, i, dp):
dp[start] = 1
return dp[start]

dp[start] = 0
return dp[start]


def wordBreak(arr, n, target):

# Clear hash map for current test case.
hashMap.clear()

# Insert all strings into hashmap.
for s in arr:
hashMap[s] = 1

# Declare dp array ans initialise all values with -1.
dp = [-1 for i in range(len(target) + 2)]

# Call wordBreakHelper to return answer.
return wordBreakHelper(target, 0, dp)

C++ (g++ 5.4)
/*

Time Complexity : O(N ^ 2)
Space Complexity : O(N)

Where N is the length of target string.
*/

#include

// Declare a hash map.
unordered_set < string > hashMap;

bool wordBreakHelper(string & s, int start, vector < int > & dp) {
// Base case
if (start == s.size()) {
return dp[start] = 1;
}

// If result is already calculated then return it.
if (dp[start] != -1) {
return dp[start];
}

// Run a loop from 1 to length of target string.
for (int i = start + 1; i <= s.size(); i++) {
/*
If substring from 0 to i exist in hash map
And remaining string recurs true.
*/
if (hashMap.find(s.substr(start, i - start)) != hashMap.end()) {
if (wordBreakHelper(s, i, dp)) {
return dp[start] = 1;
}
}
}

// If no solution exist then return false.
return dp[start] = 0;
}

bool wordBreak(vector < string > & arr, int n, string & target) {
// Clear hash map for current test case.
hashMap.clear();

// Insert all strings of a into hashmap.
for (string s: arr) {
hashMap.insert(s);
}

// Declare dp array and initialize all values with -1.
vector < int > dp(target.size() + 1, -1);

// Call wordBreakHelper to return answer.
return wordBreakHelper(target, 0, dp);
}

Java (SE 1.8)
/*

Time Complexity : O(N ^ 2)
Space Complexity : O(N)

Where N is the length of target string.
*/

import java.util.HashSet;

public class Solution {

// Declare a hash map.
static HashSet < String > hashMap = new HashSet < > ();

public static boolean wordBreakHelper(String s, int start, int[] dp) {
// Base case.
if (start == s.length()) {
dp[start] = 1;
return true;
}

// If result is already calculated then return it.
if (dp[start] != -1) {

return dp[start] != 0;
}

// Run a loop from 1 to length of target string.
for (int i = start + 1; i <= s.length(); i++) {
/*
If substring from 0 to i exist in hash
map And remaining string recurs true.
*/
if (hashMap.contains(s.substring(start, i))) {
if (wordBreakHelper(s, i, dp)) {
dp[start] = 1;
return true;
}
}
}

// If no solution exist then return false.
dp[start] = 0;
return false;
}

public static boolean wordBreak(String[] arr, int n, String target) {
// Clear hash map for current test case.
hashMap.clear();

// Insert all strings of a into hashmap.
for (String s: arr) {
hashMap.add(s);
}

// Declare dp array and initialize all values with -1.
int[] dp = new int[target.length() + 1];
for (int i = 0; i < dp.length; i++)
dp[i] = -1;

// Call wordBreakHelper to return answer.
return wordBreakHelper(target, 0, dp);
}
}
CodingNinjas
author
2y
Bottom Up DP

In this solution, we will Bottom Up dp.

Here first we will store all strings of A in a hashmap. Then we will declare a dp array and run two loops and mark dp[i] true if and only if there ex...read more

CodingNinjas
author
2y
BFS approach

In this solution, we will use a graph to represent all possible solutions. The vertices are the position of first character of a word and edges will represent the whole word.

We will use a ...read more

Add answer anonymously...
Nagarro Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter