I'm wondering if using index
or rindex
would increase the time complexity to O(n^2) in a loop such as:
for c in s:
if s.index(c) == s.rindex(c):
return c
I'm not proficient in C. However, I researched the source code for rindex.
Which can be found here . I did notice that they are using some sort of nested while loop, which technically would make the time complexity O(n^2), but that is not always the case.
Edit: Also, the code above seems to be more efficient than something like this:
h1 = dict()
for index, element in enumerate(s):
h1[element] = h1.get(element, 0) + 1
for key, value in h1.items():
if value == 1:
return key
That said, please enlighten me in understanding if the code above is O(n) or O(n^2) and why it is more efficient.
Tested with a string of length 100k.
I believe the code is O(n^2) due to using an O(n) inside a for a loop. But please correct me if I'm wrong.
I agree, you are preforming an O(n) operation with the for loop, and the s.rindex(c)
is preforming also an O(n) operation. Therefore, them multiplied is O(n^2).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.