⚔️
DSA Important Questions
  • 😇README
  • 🔫Question List
  • 🧪Formula List
  • 🗒️01 Array
    • ✅Rotate Matrix
    • ✅Max Sum Contiguous Subarray
    • Find Duplicate in Array
    • ✅Merge Intervals
    • ✅Spiral Order Matrix I
    • Repeat and Missing Number Array
    • ✅Merge Overlapping Intervals
    • ✅Set Matrix Zeros
    • ✅Spiral Order Matrix II
    • Largest Number
    • First Missing Integer
    • ✅Pascal Triangle
    • ⭐Max Distance
    • ✅Wavy Array
    • Next Permutation
    • ✅Min Steps in Infinite Grid
    • Flip
    • ⭐Find Permutation
    • ⭐Maximum Absolute Difference
    • ⭐Maximum Unsorted Subarray
    • Reorder Data in Log File
    • ✅Make equal elements Array
  • ➕02 Math
    • ✅Excel Column Number
    • ⭐Excel Column Title
    • ⭐Grid Unique Paths
    • ⭐Power Of Two Integers
    • ✅Next Similar Number
    • ⭐k-th Permutation
  • 🔍03 Binary Search
    • ⭐Median of Array
    • ⭐Square Root of Integer
    • ⭐Rotated Sorted Array Search
    • ⭐Matrix Median
    • Capacity To Ship Packages Within B Days
  • 🧵04 String
    • Implement StrStr
    • ⭐Integer to Roman
    • ⭐Roman to Integer
    • Length of Last Word
    • ⭐atoi
    • ⭐Valid IP Addresses
    • ⭐Compare Version Numbers
    • ⭐Longest Palindromic Substring
    • Count And Say
    • Reverse the String
    • Power of 2
    • 🚧KMP: Minimum Characters Required to Make a String Palindromic
    • ⭐Convert to Palindrome
    • Bulls and Cows
  • 1️⃣05 Bit Manipulation
    • Reverse Bits
    • Single Number
    • ⭐Divide Integers
    • ⭐Single Number II
    • ⭐Count Total Set Bits
    • ⭐Palindromic Binary Representation
  • ✌️06 Two Pointers
    • Merge Two Sorted Lists II
    • ⭐3 Sum
    • Remove Duplicates from sorted Array
    • ⭐Container With Most Water
    • Remove Element from Array
    • ⭐Max Continuous Series of 1s
    • Pair With Given Difference
    • ⭐Maximum Ones After Modification
  • 🔗07 Linked List
    • Swap List Nodes in Pairs
    • Rotate List
    • ⭐Reorder List
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted List
    • Add Two Numbers as Lists
    • Remove Nth Node from List End
    • ⭐List Cycle
    • Intersection of Linked Lists
    • ⭐Reverse Linked List II
    • Palindrome List
    • ⭐K reverse linked list
    • ⭐Reverse Alternate K Nodes
    • ⭐Kth Node From Middle
    • ⭐Sort Binary Linked List
    • ⭐Even Reverse
  • 📚08 Stacks and Queues
    • ⭐Rain Water Trapping
    • Generate all Parentheses
    • ⭐Largest Rectangle in Histogram
    • ⭐Min Stack
    • Redundant Braces
    • Nearest Smaller Element
    • ⭐First non-repeating character in a stream of characters
    • ✅Balanced Parantheses!
  • 🔙09 Backtracking
    • ⭐Kth Permutation Sequence
    • ⭐Combination Sum
    • Combination Sum II
    • ⭐NQueens
    • Combinations
    • ⭐Subsets II
    • Subset
    • Palindrome Partitioning
  • 💱10 Hashing
    • ⭐Longest Consecutive Sequence
    • ⭐4 Sum
    • ⭐Anagrams
    • ⭐Points on the Straight Line
    • 2 Sum
    • ⭐Valid Sudoku
    • Copy List
    • Longest Substring Without Repeat
  • 🗻11 Heaps & Maps
    • Merge K Sorted Lists
    • ⭐LRU Cache
    • ⭐Inversions
    • Distinct Numbers in Window
  • 🌳12 Tree Data Structure
    • ✅Inorder Traversal
    • ⭐Recover Binary Search Tree
    • ⭐Inorder Traversal of Cartesian Tree
    • ⭐Least Common Ancestor
    • ⭐Construct Binary Tree From Inorder And Preorder
    • Flatten Binary Tree to Linked List
    • Valid Binary Search Tree
    • ✅Preorder Traversal
    • ⭐Binary Tree From Inorder And Postorder
    • Balanced Binary Tree
    • ✅Sorted Array To Balanced BST
    • Symmetric Binary Tree
    • ✅Postorder Traversal
    • ⭐Populate Next Right Pointers Tree
    • Identical Binary Trees
    • BST Iterator
    • ZigZag Level Order Traversal BT
    • Path Sum
    • Next Pointer Binary Tree
    • Min Depth of Binary Tree
    • Root to Leaf Paths With Sum
    • ⭐Kth Smallest Element in Tree
    • ⭐2-Sum Binary Tree
    • Vertical Order traversal of Binary Tree
    • ⭐Diagonal Traversal
    • Cousins in Binary Tree
    • Path to Given Node
    • Remove Half Nodes
    • Merge two Binary Tree
    • ⭐Burn a Tree
    • Nodes at Distance K
    • Vertical Sum of a Binary Tree
    • Covered / Uncovered Nodes
  • 13 Dynamic Programming
    • Ugly Number II
    • Coin Change
    • 0 - 1 Knapsack Problem
    • Permutation Coefficient
  • 14 Greedy Algorithm
    • ⭐Gas Station
    • ⭐Majority Element
    • ⭐Distribute Candy
    • ⭐Highest Product
    • Assign Mice to Holes
    • ⭐Meeting rooms
  • 👨‍👩‍👧‍👦15 Graph
    • Clone Graph
    • Word Search Board
    • ⭐Stepping Numbers
    • Black Shapes
    • Knight On Chess Board
    • ❌Smallest Multiple With 0 and 1
    • ⭐Commutable Islands
    • Possibility of finishing all courses given pre-requisites
    • ❌Valid Path
    • Cycle in Directed Graph
    • ❌Cycle in Undirected Graph
Powered by GitBook
On this page
  • Using Map
  • Using Sorting
  • Counting Set Bits
  1. 05 Bit Manipulation

Single Number II

PreviousDivide IntegersNextCount Total Set Bits

Last updated 3 years ago

Thoughts
  • 0:00 This is another variant of the same question that as far as I remember I was able to solve in 30 seconds. Let's see how my time this one takes.

  • 1:04 I thought I got this one too. I used a map to solve this as fast as I could because I couldn't think of any other solution but I got Memory Limit Exceeded. I'll paste it here anyway.

  • 3:15 Now I can think in peace since there is no pressure to complete it in an unrealistically small amount of time.

  • 7:15 The problem statement clearly says it wants a O(n)O(n)O(n)​ solution but I really want to give sorting an attempt. Just for practice. I'll go ahead and do that.

  • 14:50 Why am I finding the sorting approach hard to implement? Am I being careless?

  • Ok, so it turns out my sorting solution has been accepted.

  • I will try thinking in terms of bit manipulation. Since this question belongs to that section.

  • 18:30 I'm not able to think of a solution. I'll take a hint.

  • 22:00 Hint couldn't help either so I saw the solution approach. Each number that appears thrice will contribute 3 1s and 0s in all the 32 bits for itself. The number that appears once will only make this contribution once. So the bits that are present 3x+1 3x+13x+1​ are the bits set by the single number.

  • Let me try using an array for this. The solution talks about using a bit-mask but that sounds too complicated.

  • 31:00 I coded something but it's not working at all. . last 15 min. Then I'll see the solution.

  • 42:00 Ok, I'm just not able to solve this. I'll see the solution now.

  • 48:00 None of the solutions they have posted in the editorial makes sense. I'll find .

  • 1:01:00 Tech Dose teaches very well. Wonder why he has so few likes.

  • 1:09:50 I've got the intuitive solution but I have no will to go for the unintuitive optimal solution. I'll just let it be for now.

Using Map

int Solution::singleNumber(const vector<int> &A) {
    map<int, int> freq;
    for(int x: A)
        freq[x]++;
        
    for(auto p: freq)
        if(p.second == 1)   
            return p.first;
        
    return -1;
}

Time Complexity: O(n)O(n)O(n)​

Space Complexity: O(n)O(n)O(n)​

Using Sorting

int Solution::singleNumber(const vector<int> &A) {
    vector<int> B(A.begin(), A.end());
    sort(B.begin(), B.end());
    int i = 0;
    while(i + 1 < A.size()) {
        if(B[i] != B[i + 1])
            return B[i];
        i = i + 3;
    }
    
    if(A.size() == 1)
        return B.front();
    else
        return B.back();
}

Time Complexity: O(nlog⁡n)O(n\log n)O(nlogn)​

Space Complexity: O(n)O(n)O(n) for duplicating array for sorting

Counting Set Bits

int Solution::singleNumber(const vector<int> &A) {
    int res = 1;
    for(int shift = 0; shift < 32; shift++) {
        int count = 0;
        for(const int &x: A) 
            count += x & (1<<shift);
        
        if(count % 3)
            res = res | (1 << shift);
    }    
}
1️⃣
⭐
I'll take it to Online GDB
a YouTube Video
Single Number II - InterviewBitInterviewBit
Logo