645. Set Mismatch

မှတ်ချက် – ဒီ Post သည် Algorithm Interview Preparation အပိုင်းဆက်ဖြစ်သည်။

ကျနော်တို့ဒီနေ့ရှင်းမယ့် ပြဿနာက 645. Set Mismatch ဆိုတဲ့ leetcode question ဘဲဖြစ်ပါတယ်။

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error.

Find the number that occurs twice and the number that is missing and return them in the form of an array.

 

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]
Example 2:

Input: nums = [1,1]
Output: [1,2]
 

Constraints:

2 <= nums.length <= 104
1 <= nums[i] <= 104


-------------------------------------------------------------------------

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findErrorNums = function(nums) {
    
};

မေးခွန်းကနေစလိုက်ကြမယ်။ ကျနော်တို့ကို integernums list တခုပေးထားမယ်။ မူလက 1 ကနေ n ထိသွားတဲ့ကောင် အဲ့မှာပြဿနာတခုကြောင့် list ထဲမှာ duplicated ဖြစ်သွားတယ်။ အဲ့တော့ကျနော်တို့က duplicated ဖြစ်တဲ့ကောင်ကိုရှာပီးတော့ အဲ့ကောင်ကို အမှန်ပြန်ပေးရမယ်။

အောက်ကအဖြေမကြည့်ခင် ကိုယ်ပိုင်စမ်းပီး ဖြေကြည့်ဖို့တိုက်တွန်းလိုပါတယ်။

အဖြေတချက်သွားလိုက်ကြရအောင်။ မေးခွန်းကိုမြန်မြန်ဖတ်ပီးတော့ သူ့ရဲ့ ဥပမာတွေကိုဘဲကြည့်ရင် ကျနော်တို့ပုံမှန်စဥ်းစားလိုက်တာက loop ပတ်ပီး duplicate ဖြစ်တဲ့ကောင်ရှာမယ်။ အဲ့ကောင်ကိုဘဲ ၁ တိုးတာ ၁ လျှော့လုပ်မယ်ဆိုပီးစဥ်းစားနိုင်တယ်။ ဒါပေမယ့်သူကအပေါ်ဆုံးမှာပြောထားတာက originally contains all the numbers from 1 to n တဲ့။ ဘာလို့အဲ့လိုလုပ်လို့မရတာလဲဆိုတာကို မျက်လုံးထဲမြင်အောင်ပြရမယ်ဆိုရင် အောက်က test case ကိုတချက်ကြည့်လိုက်ရအောင်

ဒီ Input:[4,1,3,4] ပေးထားရင်
ဒီ Expected: [4,2] value ပြန်လာတာလိုချင်

အဲ့တော့ကျနော်တို့ဒီကောင်က approach လုပ်ဖို့ရာက frequency counter နဲ့ count လိုက်မယ်။ ပီးသွားရင်အဲ့ frequency ထဲက value တွေက 1 ထက်ပိုတယ်ဆိုရင် duplicate ဖြစ်နေလို့။ အဲ့လိုမဟုတ်ဘဲ undefined ဆိုရင် miss out ဖြစ်နေတဲ့ကောင်လို့သတ်မှတ်လိုက်မယ်။ ပီးရင်အဲ့ ၂ ကိုပြန်ပေးလိုက်မယ်။ ကုဒ်ကိုကြည့်ရင်ပိုရှင်းသွားမယ်။ အောက်မှာတချက်ကြည့်ကြည့်လိုက်ကြရအောင်…

/**
 * @param {number[]} nums
 * @return {number[]}
 */
 var findErrorNums = function(nums) {
   // Define initial values
   let N = (nums.length), freqs = {}, duplicate = null, missing = null
   
   // create frequency
   nums.forEach(num => {
     freqs[num] = (freqs[num] || 0) + 1
   })
   
   // check duplicate and missing inside the frequency
   for(let i=1; i <= N; i++) {
     if(freqs[i] > 1) duplicate = i
     if(freqs[i] === undefined) missing = i
   }
   
   return [duplicate, missing]
 };

Frequency လုပ်တာကရှင်းပါတယ်။ ကျနော်တို့ object ထဲမှာမရှိရင် 0 သတ်မှတ်ပီး ၁ ပေါင်းလိုက်တာ။ Default value က ၁ ပေါ့။ ဒီလောက်ဆိုရင်တော့နားလည်ပီလို့ထင်ပါတယ်။ Time complexity က O(N) ဖြစ်ပီးတော့ space complexity ကလဲ O(n) ပါ။

Leave a Reply

Up Next:

Tree Data Structure မိတ်ဆတ်

Tree Data Structure မိတ်ဆတ်