Wednesday, June 10, 2020

Leetcode Medium: Single Number II

Here's jot of my Leetcode submission in Java to "Single Number II" problem (problem #136) on leetcode.

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer, Integer> hm = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            hm.put(nums[i], hm.getOrDefault(nums[i], 0) + 1);
        }
        
        for (int key : hm.keySet()) {
            if (hm.get(key) == 1)
                return key;
        }
        
        return -1;
    }
}
As always you can track my recent-most submissions on my leetcode page: https://leetcode.com/chandniverma/

Feel free to share your thoughts in comments.

5 comments:

  1. Two things mam.
    First iterating through hashmap i.e. O(n/3) roughly O(n) when n is large
    And then inside using hm.get() which is again O(n/3) complexity.
    Hence on upper level O(n^2).

    And also using hashmap compromises the extra memory constraint.

    ReplyDelete
    Replies
    1. FYI, all hash operations are O(1) provided the hash distributes its elements uniformly across buckets and the default implementation does it for large values of n.

      Also, there is no such thing as O(n/3). It's only O(n) as we drop all constant multipliers.

      Lastly, in my posted solution both the for loops are O(n) and O(n) + O(n) is O(n) only (again, as multipliers in complexity are ineffective essentially).

      Hope this helps!

      Delete
    2. That extra memory constraint was a followup not a hard requirement as the solution passes the problem judge!

      Delete
  2. You can simplify this considerably without resorting to hashmap by using TreeSets. Code at https://onlinegdb.com/SkRB2iA3U

    ReplyDelete
    Replies
    1. If we store the elements in a treeset, they will be O(n lg n) as TreeSet guarantees O(lg n) time in the worst case for element insertion. That will be a bottleneck operation slowing down the algorithm even further down to O(n lg n) from current O(n)!

      Delete

Featured Post

interviewBit Medium: Palindrome Partitioning II

Problem Name:  Palindrome Partitioning II Problem Description : https://www.interviewbit.com/problems/palindrome-partitioning-ii/ Problem Ap...