0

I am trying to understand, what is the best way to answer this question. My attempt is below and I am able to pass all test cases but i'm not sure if this is the best way to code the answer and most time and space efficient.

Also, i have used an OrderedDict() since I am trying to return the first character. Is there any tradeoff to using the OrderedDict() as opposed to the dict() in this question specifically? Previously, I tried this question using the dict() and it still was able to pass all test cases but i'm thinking this will not always be the case since the items in this dictionary would be unordered?

Also, is the time complexity of this solution below O(n) since we are iterating through each char of the string s?

def firstNotRepeatingCharacter(s): d1=OrderedDict() for i in s: if i not in d1: d1[i]=0 if i in d1: d1[i]=d1[i]+1 for x, y in d1.items(): if y==1: return x return "_" 
2
  • I think your answer is fine, it's in O(N) time complexity. And there is no overhead in using OrderedDict stackoverflow.com/questions/34305003/… so go ahead with this. Commented Dec 3, 2020 at 19:56
  • If you want to make it a bit shorter (in terms of code), you can replace your first if by just doing n=di.get(i, 0) and then in the next line just di[i]=n+1 Commented Dec 3, 2020 at 21:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.