I have following problem:
- I have a very long string
String str = "abcdefghiart----" - Now I want to iterate over string and want to find the first duplicate character in string
- This I can achieve with applying two for loops to search first duplicate
-
This approach works fine but iteration complexity will be very high in case string very large and only last two characters are duplicate
Now I want to minimize the complexity and optimize this code. I can use
foreachloop too to iterate but still it will be twoforeachloop. I don’t want to use any system library. Can someone help me out on this?
Here’s a method to find the first duplicate character in a string.
AS for optimization, you can optimise it by customizing Merge Sort to find duplicate value and terminate when a duplicate is found. It is a bit complicated to explain here but you’ll be able to find the first duplicate in O(nlogn) at worst case using modified merge sort algorithm.