Do String methods in Java run in O(1) time? - java

This is my code to find the length of the longest substring without repeating characters. Does this code run in O(n) time? Or does it run in O(n^2) time? I am not sure if the String methods run in O(n) time or O(1) time.
A test case includes: "pwwkewo" returning 4 because "kewo" is the the longest substring inside the string that has unique characters.
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
String sub = "";
for(int i=0; i<s.length(); i++) {
//add that char to the sub string
sub = sub + s.charAt(i);
//if we find a char in our string
if(sub.indexOf(s.charAt(i)) != -1) {
//drop any replicated indexes before it
sub = sub.substring(sub.indexOf(s.charAt(i)) + 1);
}
if(sub.length() > maxLength) {
maxLength = sub.length();
}
}
return maxLength;
}

sub.indexOf() can take linear time, since it might have to check all the characters of sub. And the length of sub is O(n) in the worst case (assuming your input has no repeating characters).
Therefore your total running time is O(n2), since the loop has n iterations and in each iteration you call indexOf().

Your code runs in O(n^2) as there is a for loop and inside it you call an indexOf() method. This in turn is O(n).
Thus your method is O(n^2).

Related

Recursion: Longest Palindrome Substring

This is a very common problem in which we would have to find the longest substring which is also a palindrome substring for the given input string.
Now there are multiple possible approaches to this and I am aware about Dynamic programming solution, expand from middle etc. All these solutions should be used for any practical usecase.
I was experimenting with using recursion to solve this problem and trying to implement the simple idea.
Let us assume that s is the given input string and i and j represent any valid character indexes of input string. So if s[i] == s[j], my longest substring would be:
s.charAt(i) + longestSubstring(s, i + 1, j - 1) + s.charAt(j)
And if these two characters are not equal then:
max of longestSubstring(s, i + 1, j) or longestSubstring(s, i, j - 1)
I tried to implement this solution below:
// end is inclusive
private static String longestPalindromeHelper(String s, int start, int end) {
if (start > end) {
return "";
} else if (start == end) {
return s.substring(start, end + 1);
}
// if the character at start is equal to end
if (s.charAt(start) == s.charAt(end)) {
// I can concatenate the start and end characters to my result string
// plus I can concatenate the longest palindrome in start + 1 to end - 1
// now logically this makes sense to me, but this would fail in the case
// for ex: a a c a b d k a c a a (space added for visualization)
// when start = 3 (a character)
// end = 7 (again end character)
// it will go in recursion with start = 4 and end = 6 from now onwards
// there is no palindrome substrings apart from the single character
// substring (which are palindrome by itself) so recursion tree for
// start = 3 and end = 7 would return any single character from b d k
// let's say it returns b so result would be a a c a b a c a a
// this would be correct answer for longest palindrome subsequence but
// not substring because for sub strings I need to have consecutive
// characters
return s.charAt(start)
+ longestPalindromeHelper(s, start + 1, end - 1) + s.charAt(end);
} else {
// characters are not equal, increment start
String s1 = longestPalindromeHelper(s, start + 1, end);
String s2 = longestPalindromeHelper(s, start, end - 1);
return s1.length() > s2.length() ? s1 : s2;
}
}
public static String longestPalindrome(String s) {
return longestPalindromeHelper(s, 0, s.length() - 1);
}
public static void main(String[] args) throws Exception {
String ans = longestPalindrome("aacabdkacaa");
System.out.println("Answer => " + ans);
}
For a moment let us forgot about time complexity or runtime. I am focused towards making it work for simple case above.
As you can see in the comments I got the idea why this is failing but I tried hard to rectify the problem following the exactly same approach. I don't want to use loops here.
What could be the possible fix for this following same approach?
Note: I am interested in the actual string as answer and not the length. FYI I had a look at all the other questions and it seems no one is following this approach for correctness so I am trying.
Once you have a call wherein s[i] == s[j], you could flip a boolean flag or switch to a modified method that communicates to child calls that they can no longer use the "don't match, try i + 1 and j - 1" branch (else condition). This ensures you're looking at substrings, not subsequences, for the remainder of the recursion.
Secondly, for the substring variant, even if s[i] == s[j], you should also try i + 1 and j - 1 as if these characters didn't match, because one or both of these characters might not be part of the final best substring between i and j. In the subsequence version, there's never any reason not to add any matching characters to the current palindromic subsequence for the range i to j, but that's not always the case with substrings.
For example, given input "aabcbda" and we're at a call frame where i = 1 and j = length - 1, we need to maximize over three possibilities:
The best substring includes both 'a' characters. Call the subroutine with the flag that says we have to consume from both ends on down and can no longer try skipping characters.
The best substring might still include s[i] but not s[j], try j - 1.
The best substring might still include s[j] but not s[i], try i + 1.
Another observation: it might make more sense to pass best indices up the helper call chain, then grab the longest palindromic substring based on these indices at the very end in the wrapper function.
On a similar note, if you're struggling, you might simplify the problem and return the longest palindromic substring length using your recursive method, then switch to getting the actual substring itself. This makes it easier to focus on the subsequence logic without the return value complicating things as much.
It is much easier to use loops here, rather than recursion, something like this:
public static void main(String[] args) {
System.out.println(longestPalindrome("abbqa")); // bb
System.out.println(longestPalindrome("aacabdkacaa")); // aca
System.out.println(longestPalindrome("aacabdkaccaa")); // acca
}
public static String longestPalindrome(String str) {
String palindrome = "";
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
String substring = str.substring(i, j);
if (isPalindrome(substring)
&& substring.length() > palindrome.length()) {
palindrome = substring;
}
}
}
return palindrome;
}
public static boolean isPalindrome(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
return false;
}
}
return true;
}

bigO time complexity of algorithm to find Longest Substring Without Repeating

public int lengthOfLongestSubstring(String s) {
//using a Collection to check if duplicate elements exist.
int count = 0;
int max = 0;
ArrayList<String> str = new ArrayList();
for(int i =0; i< s.length();i++){
String temp = Character.toString(s.charAt(i));
if(str.contains(temp)){
int idx = str.indexOf(temp);
for(int j = 0; j<= idx;j++) // clear all the elements before the duplicate elements, inluding the
str.remove(0); //duplicate. So, no elements collision in the new list.
str.add(temp);
count = str.size(); // update the count - the size of the new list.
}else {
str.add(temp);
count++;
if(count>max)
max=count;
}
}
return max;
}
Hi, what are time and space analysis? I think space complexity is O(n), but time complexity depends on the numbers of duplicate characters because we remove element only if we meet the repeated character.
Thank you!
The space complexity is O(n^2) as you said.
But the time complexity will be O(n^2) because you are doing a linear search on arraylist every time to find if the char is repeated or not
if(str.contains(temp)) at this line. which is O(k) where k is the size of the arrayList
Consider an example of all unique elements
for i = 1 you will take 1 operation
for i = 2 you will take 2 operations
for i =n you will take n operations
total time complexity = O(1 + 2 + ... +n) = O(n^2)

reading text on file and verifying through an array on java

So basically i have to verify how many times words are counted within a file on an array.
Edit#2 ( i will run this program through cmd after)
This program takes a number of command line arguments:
1) The file to open
2+) The words to search for and count
If you don’t give it any words to search for, it defaults to these words: "doctor",
"frankenstein", "the", "monster", "igor", "student", "college", "lightning",
"electricity", "blood", and "soul".
You may want to run it with fewer or different words, eg:
$ java ReadSearchAndSort frankenstein.txt frankenstein doctor igor monster
Edit/Update*:
If we consider the simple program:
public class CopyCat{
public static void main(String[] arguments){
for (int ii = 0; ii < arguments.length; ii++){
System.out.println("Argument "+ ii + " = " +
arguments[ii]);
}
}
}
Then if we run it as such:
$ java CopyCat a b c
we will get the following output
Argument 0 = a
Argument 1 = b
Argument 2 = c
Using this as your basis:
Get the first argument and store it in a String named filename
● Get the rest of the arguments and place them in a String array named
queryWords (this should be of the correct size to hold all of the words to count,
and there should be no maximum size — ignoring memory demands of your
system)
Loop through the scanner while things remain in the file ( i.e. hasNext() is true)
and get the next word in the file (i.e. call next())
● Put the word in an array — note, you will need to constantly resize the array —
○ So first instantiate an empty array, outside of the for loop
String[] words = new String[0]();
○ Then, when you read a word, resize the array using Arrays.copyof, i.e.
words = Arrays.copyOf(words, words.length+1)
○ Then place the word in the last spot of the array
■ … but first, we want to make it lower case
word = word.toLowerCase();
■ and remove all of the non-letters
word = word.replaceAll("[^a-zA-Z ]", "");
For each word in our words list, we need to go through the array of words we have read
in, and count each instance. To do this we will make a helper function:
Implementing the function ​countWordsInUnsorted
Create a counter variable to record how many times we have seen a word. Create a
loop that iterates over every word in the array. Each time a word matches the query word, increment the counter. We need to use the equals method, since we care about whether two strings have the same characters in them, not that they are the exact same
object.
Once you’ve completed the two tasks above, you can run your code. Verify that
"frankenstein" appears 26 times
Overall im having trouble understanding the directions and how i should order my code so its understandable. If you can help in anyway i would appreciate it. I know its quite long, but this isnt even whole assignment so its shortened.
EDIT 9/7/18 updates instructions
Timing things in Java
How long did your code take to run?
In this assignment, we will see some search algorithms run faster than others. To seehow much faster, we will record how long the code takes to run.
Here is an example of timing code:
// Look at the clock when we start
long t0 = (new Date()).getTime();
for (var i = 0; i < 100000; i++) {
// Do something that takes time
}
// Look at the clock when we are finished
long t1 = (new Date()).getTime();
long elapsed = t1 - t0;
System.out.println("My code took " + elapsed + "milliseconds to
run.")
This is already set up for you in main and will output how long your code took to run.
Your job is to implement and call your functions, and make sure that they are working
correctly. If you look in the starter code, you’ll see that we’re running your two different
search and count methods 100 times, so as to get a good average value for how long it
takes. We’re only do the sort once, as sorting the array of 75289 words already takes
awhile.
4. Sorting an array of words with Merge Sort
(35 points)
● Implement mergeSort (Do not​ use Java's built-in Array.sort for this assignment)
● Call your new method in main
● Checking if you are right:​ the words (after SORTED in the output) will be in
alphabetical order.
Implementing ​mergeSort
Implement a mergeSort method that sorts an array of strings. The signature for this
method should be:
public static void mergeSort(String[] arrayToSort, String[]
tempArray, int first, int last)
The first argument is the String[] to sort, the second argument is an empty temporary
array that should be the same size as the array to sort, the third argument is the starting
index for the portion of the array you want to sort, and the fourth argument is the ending
index for the portion of the array you want to sort.
Note that the version of mergeSort we’ll be implementing sorts arrayToSort in place.
This means that you pass an unsorted array in to mergeSort and after the call that
same array is now sorted.
Note that mergeSort involves comparing to values to see which is larger. With numbers
you can just use < or > to compare them.
if you have two Strings s1 and s2, then:
● s1.compareTo(s2) == 0 if s1 and s2 contain the same string.
● s1.compareTo(s2) < 0 if s1 would be alphabetically ordered before s2.
● s1.compareTo(s2) > 0 if s1 would be alphabetically ordered after s2.
Calling ​mergeSort​ in ​main
To call mergeSort in main, you first need to create a temporary string array that is the same length as allWords.
We want to sort the whole array, so the third argument should be the index of the first word in allWords and the fourth argument should be the
index of the last word in allWords. The four arguments to call mergeSort with are then:
● The array we’re sorting, which is allWords.
● Our new temporary array we’ve created that’s the same length as allWords.
● The index of the first word in allWords (hint: what’s always the index of the very first element of an array?).
● The index of the last word in allWords (hint: if you know the length of an array, you can easily compute the index of the last element).
Checking you are right
Did this sort the array of words? The program prints every 500th word. Do they look
sorted?
5. Counting words (with Binary Search) and timing it
(35 points)
● Implement
public static int binarySearch(String[] sortedWords,
String query, int startIndex, int endIndex)
● Implement
public static int getSmallestIndex(String[] words,
String query, int startIndex, int endIndex)
● Implement
public static int getLargestIndex(String[] words, String
query, int startIndex, int endIndex)
● Call getSmallestIndex and getLargestIndex in main to get the smallest and
largest indices at which the word you’re looking for appears in the sorted array.
Use these two values to compute how many times that word appears.
● Checking if you are right:​ you will get the same values as in the first search section, but much faster.
Implementing ​binarySearch
The arguments to binarySearch are:
● The sorted array of words to search in.
● The word to search for.
● The index in the array at which to start searching.
● The index in the array at which to stop searching.
Binary search returns the array index where it found the word. If the word only appears once in the array, then this index will be where it occurs.
But if the word appears multiple times in the sorted array (so all the instances of the word will be next to eachother in the array), then this index will be to one of the words in the middle of the group.
The binary search algorithm doesn’t guarantee that this will be the first element in the group or the last element in the group.
So we need to implement some other methods to do this.
Implementing ​getSmallestIndex
The method getSmallestIndex will be a recursive method that uses the
binarySearch method to find the smallest index for which a word is found in the array.
The outline for this method is:
● Use binarySearch to find an index to the word. If the index binarySearch
returns is -1, then the word wasn’t found and getSmallestIndex should just
return -1. This is the base case.
● If binarySearch did find the word, then recursively call getSmallestIndex on
the portion of the array before where the word was found. This is from index 0 up
to (but not including) the index where the word was found. If this returns -1 then
we know we already had the smallest index, otherwise the recursive call to
getSmallestIndex found the smallest index and we should return that. This is
the recursive case.
Implementing ​getLargestIndex
The method getLargestIndex will be a recursive method that uses the binarySearch
method to find the largest index for which a word is found in the array. The outline for
this method is very similar to the outline above for getSmallestIndex, except that the
recursive call should search the portion of the array starting after where binarySearch
has found the word.
Using ​getSmallestIndex​ and ​getLargestIndex​ in ​main​ to count words
Since the array that you’re working with has been sorted by this point, all the same
words appear next to each other (e.g. all 26 appearances of the word "frankenstein"
are next to each other in the array). So if you’ve found the smallest and largest index for
a word, then you can just subtract the two indices to count the words! But it’s not quite
word appears only once (so the first and last index are the same) and the case where
the word doesn’t appear at all.
Checking if you are right
Check that you’re getting the same answers as the naive approach that iterates through
the whole array. Also, look to see how much faster this approach is to the naive
approach!
Example arguments and output
$​ java ReadSearchAndSort frankenstein.txt student college frankenstein blood the
Arguments: use ''student,college,frankenstein,blood,the'' words, time 100 iterations, search for words:
student,college,frankenstein,blood,the
NAIVE SEARCH:
student:2
college:3
frankenstein:26
blood:19
the:4194
96 ms for 500 searches, 0.192000 ms per search
SORTING:
38 ms to sort 75097 words
SORTED (every 498 word): a a aboard affection all although ancient and and and and and angel approached
as asked attended be been believe boat but but by cause clerval comprehensive continued country dante
decay desire died do duvillard end escape exception eyes favourite few flourishing for frankenstein from
girl grief had happiness have he heart her his histories however i i i i i ice impossible in in
inhabitants investigating it its know leaves limbs love man me me might mixture most my my my my nature
no not oatmeal of of of of of old on or over passed philosophy possession profoundly rain regular
resolve room saved seem shape should smiles some spirit straw sun tavernier that that the the the the
the the the the the then thick those time to to to to town uncle upon vessels was was was were when
which while will with with would you you
BINARY SEARCH:
student:2
college:3
frankenstein:26
blood:19
the:4194
6 ms for 500 searches, 0.012000 ms per search
Of course the actual timing for running the searches and sort will vary on your computer,
depending on how fast your computer is and how many other processes are running on it.
EDIT 9/7/18
import java.io.*;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class ReadSearchAndSort {
public static void main(String[] args) throws FileNotFoundException {
String filename = args[0];
int n = args.length - 1;
String[] queryWords = null;
String[] allWords = readWords("frankenstein.txt");
String[] tempAllWords = new String[allWords.length];
if (n > 0) { //if user provides the querywords
queryWords = new String[n];
for (int i = 1; i < args.length; i++) {
queryWords[i - 1] = args[i];
}
} else { //if user doesn't provide querywords
queryWords = new String[]{"doctor", "frankenstein", "the", "monster", "igor", "student", "college", "lightning", "electricity", "blood", "soul"};
}
ReadSearchAndSort.readWords("C:/Users/Jordles/IdeaProjects/TimeConversionToSecond.java/out/production/GettingStarted/cs141/frankenstein.txt");
int timingCount = 100;
System.out.println("\nArguments: use '" + String.join(",", queryWords) + "' words, time " + timingCount + " iterations, search for words: " + String.join(",", queryWords) + "\n");
System.out.println("NAIVE SEARCH:");
// Record the current time
long t0 = new Date().getTime();
// Time how long it takes to run timingCount loops
// for countWordsInUnsorted
for (int j = 0; j < timingCount; j++) {
for (int i = 0; i < queryWords.length; i++) {
int count = countWordsInUnsorted(allWords, queryWords[i]);
if (j == 0) {
System.out.println(queryWords[i] + ":" + count);
}
}
}
long t1 = (new Date()).getTime();
long timeToSearchNaive = t1 - t0;
int searchCount = timingCount * queryWords.length;
// Output how long the searches took, for how many searches
// (remember: searches = timingcount * the number of words searched)
int searches = timingCount * 500;
System.out.printf("%d ms for %d searches, %f ms per search\n", timeToSearchNaive, searchCount, timeToSearchNaive * 1.0f / searchCount);
// Sort the list of words
System.out.println("\nSORTING: ");
mergeSort(allWords, tempAllWords, 0, allWords.length);
long t2 = (new Date()).getTime();
// Output how long the sorting took
long timeToSort = t2 - t1;
System.out.printf("%d ms to sort %d words\n", timeToSort, allWords.length);
// Output every 1000th word of your sorted wordlist
int step = (int) (allWords.length * .00663 + 1);
System.out.print("\nSORTED (every " + step + " word): ");
for (int i = 0; i < allWords.length; i++) {
if (i % step == 0)
System.out.print(allWords[i] + " ");
}
System.out.println("\n");
System.out.println("BINARY SEARCH:");
// Run timingCount loops for countWordsInSorted
// for the first loop, output the count for each word
for (int j = 0; j < timingCount; j++) {
for (int i = 0; i < queryWords.length; i++) {
int count = countWordsInUnsorted(allWords, queryWords[i]);
if (j == 0) {
System.out.println(queryWords[i] + ":" + count);
}
}
}
long t3 = (new Date()).getTime();
long timeToSearchBinary = t3 - t2;
System.out.printf("%d ms for %d searches, %f ms per search\n", timeToSearchBinary, searchCount, timeToSearchBinary*1.0f/searchCount);
}
public static String[] readWords(String fileName) throws FileNotFoundException{
String[] words = new String[0];
int i = 0;
File file = new File(fileName);
Scanner input = new Scanner(file, "UTF-8");
input.useDelimiter("\\s+|\\-");
while(input.hasNext()){
String word = input.next();
word = word.toLowerCase();
word = word.replaceAll("[^a-zA-Z ]", "");
words = Arrays.copyOf(words, words.length + 1);
words[i++] = word;
}
return null;
}
public static int countWordsInUnsorted(String[] WordsToCount, String countedWord){
if ((countedWord == null) || (WordsToCount == null)){
return 0;
}
int counter = 0;
for( String word : WordsToCount){
if (word.equals(countedWord)){
counter++;
}
}
return counter;
}
public static void mergeSort(String[] arrayToSort, String[] tempArray, int first, int last){
if (first == last){
return;
}
int mid = (first + last)/2;
mergeSort(arrayToSort, tempArray, first, mid);
mergeSort(arrayToSort, tempArray, mid + 1, last);
merge(arrayToSort, tempArray, first, mid, mid + 1, last);
}
public static void merge(String[] arrayToSort, String[] tempArray, int first, int mid, int mid1, int last){
int j = first;
int k = mid1;
int l = first;
do{
if (tempArray[j].compareTo(tempArray[k]) < 0){
arrayToSort[l] = tempArray[j];
j++;
}
else{
arrayToSort[l] = tempArray[k];
k++;
}
}
while (j <= mid && k <= last){
}
}
public static int binarySearch(String[] sortedWords, String query, int startIndex, int endIndex){
if (startIndex > endIndex){
}
int mid = (startIndex + endIndex)/2;
if(query.compareTo(sortedWords[mid]) == 0){
return;
}
if (query.compareTo(sortedWords[mid]) < 0){
binarySearch(sortedWords, query, startIndex, mid -1 );
}
if (query.compareTo(sortedWords[mid]) > 0){
binarySearch(sortedWords, query, mid + 1, endIndex);
}
return -1;
}
public static int getSmallestIndex(String[] words, String query, int startIndex, int endIndex){
return -1;
}
public static int getLargestIndex(String[] words, String query, int startIndex, int endIndex){
return -1;
}
public static int countWordsInSorted(String[] wordsTocount, String countedWord){
return 0;
}
}
In the readWords method you should call .toLowerCase() and .replaceAll() only after reading the word form the file.
Edit: The return null; must not be the only return of the method, otherwise you're just throwing away everything the method did. You could use it to handle error, but I strongly suggest to return an empty array.
If you return an empty array (or collection), you avoid surprising consumers (whoever call your method) of this method with an unintentional NullPointerException, so so they don't have to guard against it.
Take also a look at the tutorial for try-with-resources statement I've used.
public static String[] readWords(final String filename) {
// Check on input
if (filename == null) {
return null;
}
String[] words = new String[0];
int i = 0; // index of the first empty position in the array
final File inputFile = new File(filename);
try (Scanner in = new Scanner(inputFile)) {
in.useDelimiter("\\s+|\\-");
while (in.hasNext()) {
String word = in.next().toLowerCase();
word = word.replaceAll("[^a-z ]", ""); // No need of A-Z since we called .toLowerCase()
words = Arrays.copyOf(words, words.length + 1);
words[i++] = word; // Put the current word at the bottom of the array, then increment the index
}
} catch (final FileNotFoundException e) {
System.err.println("The file " + filename + " does not exist");
return null;
}
return words;
}
The method is very simple, I suggest using the enhanced for loop.
Please also consider Java naming conventions: variable name should start with lowercase letter.
Edit: same here about the return 0;. It must not be the only return of the method.
public static int countWordsInUnsorted(final String searchedWord, final String[] words) {
// Check on input
if ((searchedWord == null) || (words == null)) {
return 0;
}
int count = 0;
for (final String word : words) {
if (word.equals(searchedWord)) {
count++;
}
}
return count;
}
Edit4:
This program takes one command line argument: the words to search for and count.
java SearchAndSort "frankenstein,doctor,igor,monster"
Since the assignement uses a comma as separator, you can use String.split() to get the array of strings.
Due to the need of calculating the elapsed time, you cannot search and print the words: the print operation is very time expensive, so it would distort the result. That's why I used an array of int to store the count of every word.
int[] wordsCounter = new int[queryWords.length];
In order to calculate the time per search, you need a double, but if you do an arithmetic operation between long, you'll always get a long. That's why you need to cast at least one operand to double.
double timePerSearch = ((double) elapsedTime) / totalSearches;
Refactored main method:
public static void main(final String[] args) {
// Default words to search for
String queryWordsString = "doctor,frankenstein,the,monster,igor,student,college,lightning,electricity,blood,soul";
if (args.length > 0) { // If the user provided query words
queryWordsString = args[0];
}
final String[] queryWords = queryWordsString.split(","); // split the string into an array
System.out.println("SEARCH AND SORT");
System.out.println();
System.out.println("Searching and counting the words " + queryWordsString); // print the words to search for
System.out.println();
// Just the name of the file if it's in the same directory of program
// The absolute path if they are in different directory
final String filename = "frankenstein.txt";
// Read words from file
final String[] words = SearchAndSort.readWords(filename);
if (words == null) {
return;
}
final int[] wordsCounter = new int[queryWords.length];
// Store the starting time
final long startTime = System.currentTimeMillis();
// Search the words and store their count
for (int i = 0; i < queryWords.length; i++) {
final int count = SearchAndSort.countWordsInUnsorted(queryWords[i], words);
wordsCounter[i] = count;
}
final long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("NAIVE SEARCH:");
// Print how many time each word appears
for (int i = 0; i < queryWords.length; i++) {
System.out.println(queryWords[i] + ": " + wordsCounter[i]);
}
final int totalSearches = queryWords.length * words.length;
final double timePerSearch = ((double) elapsedTime) / totalSearches;
// Print the elapsed time in ms
System.out.println(elapsedTime + " ms for " + totalSearches + " searches, " + timePerSearch + " ms per search");
}
Edit4:
long t0 = ( new Date()).getTime();
for (var i = 0 ; i < 100000 ; i++) {
// Do something that takes time
}
In this example the 100000 isn't a new variable, it's the standard upper limit of the for loop you're going to use. It's queryWords.length for NAIVE SEARCH: block and words.length for SORTING: block.
Edit:
// Record the current time
long t0 = (new Date()).getTime();
Don't do this. If you want to measure elapsed time, you should use long t0 = System.nanoTime(). From the documentation
Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.
This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().
[...]
The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.
For example, to measure how long some code takes to execute:
Probably you would read System.currentTimeMillis() documentation too.

I am getting timeout error in the following code. How to reduce the complexity of the code?

You are provided with a string s and an integer k.
You have to find another string t which satisfies the following conditions:
t must be a subsequence of s.
Every character t in must occur at least k times.
The length of t must be as large as possible.
If there are multiple strings for t with largest possible length, pick the
lexicographically smallest one.
For example, let's say the string is s=hackerrank and k=2.
The solution for this is t=akrrak. Here t is a subsequence of k, it conta
ins the characters a,k and r repeated at least k=2 times. And, it is the
only longest possible subsequence that satisfies the conditions.
Input Format
The first line contains a string s denoting the original string.
The second line contains an integer k.
Constraints
String s will only contain lowercase English characters.
Every input will have a valid solution.
Output Format
Print the string t on a single line.
Sample Input 0
hackerrank
2
Sample Output 0
akrrak
Explanation 0
In 'akrrak', all the characters occur exactly 2 times.
I have used 2 for loops for comparing each character with the whole string. if the count for any character is greater than value of k then that particular character is stored in an char array and is printed as a result.
I have used null in method as return value. How to return the string as a result?? How to resolve the timeout issues??
How to reduce the complexity of the program??
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static String subsequenceAgain(String s, int k) {
// Complete this function
char ch[] = new char[s.length()]; //initializing character array
int len = s.length(); //calculating length of string
for (int i = 0; i < len; i++) {
int count = 0;
for (int j = 0; j < len; j++) {
if (s.charAt(i) == s.charAt(j)) // making comparison with each character
count++;
}
if (count >= k) {
ch[i] = s.charAt(i);
System.out.print(ch[i]); // subsequence to be printed
}
}
return "null";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in .next();
int k = in .nextInt();
String result = subsequenceAgain(s, k);
in .close();
}
}
How to return the string as a result??
Right now you are printing the solution as you go. Instead, you need to save it to a variable. I think a StringBuilder would be appropriate here. You can declare it like this:
StringBuilder result = new StringBuilder();
You can add to it like this:
result.append(ch[i]);
And return the underlying String like this:
return result.toString();
How to resolve the timeout issues??
The code you have shouldn't be timing out, unless your input is extremely large or your timeout period is extremely short.
How to reduce the complexity of the program??
The complexity of your current program appears to be O(n^2), which isn't unreasonable. There are ways to make it O(n) but unless your input is very large I don't think it would really make a difference.

More efficient way to find all combinations?

Say you have a List of Strings or whatever, and you want to produce another List which will contain every possible combination of two strings from the original list (concated together), is there any more efficient way to do this other than using a nested for loop to combine the String with all the others?
Some sample code:
for(String s: bytes) {
for(String a: bytes) {
if(!(bytes.indexOf(a) == bytes.indexOf(s))) {
if(s.concat(a).length() == targetLength) {
String combination = s.concat(a);
validSolutions.add(combination);
}
}
}
}
The time for execution gets pretty bad pretty quickly as the size of the original list of Strings grows.
Any more efficient way to do this?
You can avoid checking i != j condition by setting j = i + 1. Also, things like bytes.length() get evaluated at each iteration of both loops - save it into a value and reuse. Calling a.length() inside the loop asks for a length of the same string multiple times - you can save some runtime on that as well. Here are the updates:
int len = bytes.length();
int aLength;
String a, b;
for(int i=0; i<len; i++) {
a = bytes[i];
aLength = a.length();
for(int j=i; j<len; j++) {
b = bytes[j];
if (b.length() + aLength == targetLength) {
validSolutions.add(b.concat(a));
validSolutions.add(a.concat(b));
}
}
}
Edit: j = i because you want to consider a combination of a string with itself; Also, you'd need to add a.concat(b) as well since this combination is never considered in the loop, but is a valid string
You can't get Better than O(N^2), because there are that many combinations. But you could speed up your algorithm a bit (from O(N^3)) by removing the indexOf calls:
for(int i=0; i<bytes.length(); i++) {
for(int j=0; j<bytes.length(); j++) {
string s = bytes[i];
string a = bytes[j];
if (i != j && s.length() + a.length() == targetLength) {
validSolutions.add(s.concat(a));
}
}
}
In addition to what Jimmy and lynxoid say, the fact that the total length is constrained gives you a further optimization. Sort your strings in order of length, then for each s you know that you require only the as such that a.length() == targetLength - s.length().
So as soon as you hit a string longer than that you can break out of the inner loop (since all the rest will be longer), and you can start at the "right" place for example with a lower-bound binary search into the array.
Complexity is still O(n^2), since in the worst case all the strings are the same length, equal to half of totalLength. Typically though it should go somewhat better than considering all pairs of strings.

Categories

Resources