algorithm - Count distinct array entries [with no add memory nor array changes] -
task count unique numbers of given array. saw numerous similar questions on so, here have additional requirements, weren't stated in other questions:
- amount of allowed additional memory o(1)
- changes array prohibited
i able write quadratic algorithm, agrees given constraints. keep wondering, may 1 better on such problem? thank time.
algorithm working o(n^2)
def count(a): unique = len(a) ind = 0 while ind < len(a): x = a[ind] = ind+1 while < len(a): if a[i] == x: unique -= 1 break += 1 ind += 1 print("total uniques: ", unique)
this similar problem follow-up question in chapter 1 (arrays , strings) cracking coding interview:
implement algorithm determine if string has unique characters. if cannot use additional data structures?
the answer (to follow-up question) if can't assume array (namely, not sorted, don't know size, etc.), there no algorithm better showed.
that being said, may think relaxing constraints little bit, make more interesting. example, if have upper bound on array size, use bit vector keep track of values you've read before while traversing array, although not strictly o(1)
solution when comes memory usage (one argue knowing maximum array size, memory usage constant, , o(1)
, little bit of cheating). similarly, if array sorted, solve in o(n)
going through each element @ time , check if neighbors different numbers.
Comments
Post a Comment