Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

What is the big O complexity of the following java algorithm? The algorithm is used to take a String s of uppercase letters and break

What is the big O complexity of the following java algorithm?

The algorithm is used to take a String s of uppercase letters and break them into substrings of English words. I'm a bit confused about the complexity, though. My initial thought was O(n2) since the second for loop must check the dictionary for each substring to see if it is in the dictionary, but i've also heard that each call to str.substring(0, i) before the recursive portion may also constitute another n checks. If that is the case, the complexity would be O(n3).

Can someone help me analyze this algorithm for it's complexity? Thanks.

class WordBreak { static String[] result; static String[] dictionary = {"I", "THE", "ABORT", "PLAN", "MEET", "CONFIRM", "AT", "DARK", "CABIN", "PROCEED", "MISSION", "MISS", "CHOCOLATE", "ALIENS", "CANNIBALS", "SAUCE"}; public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); int size = str.length(); result = new String[size]; print(str, 0); } //method which recursively breaks input string into substrings  //which are stored in an array and, if they are English words, then printed  static void print(String str, int ind) { //each recursive call shortens the input string until length is 0  int length = str.length(); //if length is 0, then print the resulting substrings to decode  //the message  if(length == 0) { for(int i = 0; i < ind; i++) { System.out.print(result[i] + " "); } System.out.println(); return; } //if a valid substring of the dictionary, add it to result array and recur  for(int i = 1; i <= length; i++) { if(valid(str.substring(0, i)) == true) { result[ind] = str.substring(0, i); print(str.substring(i), ind + 1); } } } //valid function returns true iff string s is an English word (in the dictionary)  static boolean valid(String s) { boolean result = false; for(int i = 0; i < dictionary.length; i++) { if(s.equals(dictionary[i])) { result = true; break; } } return result; } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

Understanding Group Leadership Culture and Group Leadership

Answered: 1 week ago