DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on ā€¢ Edited on

Leetcode - 645. Set Mismatch

Basically we need to return duplicated item and the missing item in array .

since the numbers are from 1 to n

their total sum will be n*(n+1)/2 (šŸ˜… mathematics)

Approach is simple just use a for loop and push each item in a new array only if its not in the new array , if its already present in new array then i don't push it instead store the duplicated item in a variable

i named the new array as - arrUnique
storing duplicated item in variable dup

the rest is understandable from code just have a look and try to understand

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findErrorNums = function(nums) {
    const arrUnique = [] ;
    let dup = 0;
    let remainingSum = 0;
    const n = nums.length;
    nums.forEach((num)=>{
        if(arrUnique.includes(num)){
            dup = num
        }else{
            remainingSum+=num;
            arrUnique.push(num)
        }
    })


    const sum = (n * (n+1)) / 2
    return [dup,(sum-remainingSum) ]
};
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay