Question:
This is the question: https://leetcode.com/problems/contains-duplicate-ii/Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i – j) <= k.
My code:
EDIT:
I realised the problem is with this line: console.log([i, j]). If I comment it out, there is no problem with submission. But I’m not quite sure why that line is causing the time limit exceeded error. Any help will be highly appreciated!
Answer:
Leetcode and similar sites often provide huge data sets as input. In such cases, an unnecessarily computationally complex algorithm can take too much processing time to complete. That may be what’s happening here.You have a nested loop – if the input array contains 1000 items, that’s on the order of 1000 * 1000 iterations. Use a different, less expensive algorithm – such as by iterating over the input only once. One possible approach is
var containsNearbyDuplicate = function(nums, k) {
const numsByLastIndex = {};
for(let i = 0; i < nums.length; i++) {
const num = nums[i];
if (numsByLastIndex[num] !== undefined && i - numsByLastIndex[num] <= k) {
return true;
}
numsByLastIndex[num] = i;
}
return false;
};
[/code]
Another issue is that logging in the Node CLI, if you do a ton of logging, can slow things down. Sometimes, logging can even take up most of the processing time of your script. It’s not needed to perform the task, so feel free to remove it.
If you have better answer, please add a comment about this, thank you!