top of page

Word Break Solution using dp memoization

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

Note :
You can use any string of array multiple times.
Examples :
array =[“dev”, ”porta”, “is”, “awesome”]  target = “devporta”
Ans = true as we use “dev” and “porta” to form “devporta”




import java.util.* ;
import java.io.*; 
public class Solution {
    public static Boolean wordBreak(String[] arr, int n, String target) {
        if(target.isEmpty())
           return true;

        int[] dp = new int[target.length()+1];
        Arrays.fill(dp, -1);
        return findAns(Arrays.asList(arr), n, target, dp);
    }

    public static Boolean findAns(List<String> arr, int n, String target, int[] dp){
         if(target.isEmpty()){
             dp[0] = 1;
             return true;
         }

         int length = target.length();

         if(dp[length]!=-1)
           return dp[length]==1;

        for(int i=1;i<=length;i++){
            String word = target.substring(0,i);
            if(arr.contains(word)){
                Boolean ans = findAns(arr, n, target.substring(i), dp);
                if(ans){
                    dp[length] = 1;
                    break;
                }else{
                    dp[length] = 0;
                }
            }else{
                dp[length] = 0;
            }
        }
        return dp[length]==1;
    }
}

Recent Posts

See All
Partition Array for Maximum Sum

Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has...

 
 
 

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page