1

I am trying to find whether a part of given string A can be or can not be rearranged to given string B (Boolean output).
Since the algorithm must be at most O(n), to ease it, I used stringA.retainAll(stringB), so now I know string A and string B consist of the same set of characters and now the whole task smells like regex.
And .. reading about regex, I might be now having two problems(c).
The question is, do I potentially face a risk of getting O(infinity) by using regex or its more efficient to use StreamAPI with the purpose of finding whether each character of string A has enough duplicates to cover each of character of string B? Let alone regex syntax is not easy to read and build.
As of now, I can't use sorting (any sorting is at least n*log(n)) nor hashsets and the likes (as it eliminates duplicates in both strings).
Thank you.

Shved
  • 35
  • 7
  • Acc to https://stackoverflow.com/questions/24754881/what-is-the-time-and-space-complexity-of-method-retainall-when-used-on-hashsets retainAll is O(n) – Stefan Dec 06 '18 at 09:37
  • Only on `HashSet` but you say you can't use hashes. – talex Dec 06 '18 at 09:41
  • @talex Exactly, using hashes eliminates number of occurrences for each character. In case string B has a character that occurs more than corresponding character in string B, Hashset will return true, but it is actually false. – Shved Dec 06 '18 at 09:45

1 Answers1

3

You can use a HashMap<Character,Integer> to count the number of occurrences of each character of the first String. That would take linear time.

Then, for each Character of the second String, find if it's in the HashMap and decrement the counter (if it's still positive). This will also take linear time, and if you manage to decrement the counters for all the characters of the second String, you succeed.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you, Eran. Does this mean I compare each character in string B with each element of the HashMap? If so, isn't that O(n^2)? – Shved Dec 06 '18 at 09:48
  • @Shved no, for each character of B you call `Integer count = map.get(B.charAt(i));` which takes O(1) time (and if `count` is not null and > 0, you call `map.put(B.charAt(i),count-1)`, which also takes `O(1)` time). Therefore the total time will be linear. – Eran Dec 06 '18 at 09:52