A well commented O(1) extra space and O(n) time code :D

  • 0
    class Solution {
        vector<int> findDuplicates(vector<int>& nums) {
            // calculte size of vector
            int n = nums.size();
            for(int i=0;i<n;i++){
                // swap till all nums[i] come to their original places
                while(nums[i]!=nums[nums[i]-1])   swap(nums[i],nums[nums[i]-1]);
            vector<int> ans;
            // all elements which are between 1 and n come to their original places so we can skip those
            for(int i=0;i<n;i++){
                if(nums[i]!=i+1)    ans.push_back(nums[i]);
            return ans;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.