• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Bug in leetcode, javascript 219. Contains Duplicate II

Resolved: Bug in leetcode, javascript 219. Contains Duplicate II

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

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:
Example 2:
Example 3:
I can’t think of any fringe cases which is causing the submission to exceed time limit. I’m aware that there are other ways to solve this problem, but I would like to know what’s wrong with my code. Any help will be highly appreciated!
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]

When I try the above code, the time required has changed from on the order of 9 seconds (which may be close to the limit) down to 1/4 of a second.
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!

arrays javascript logic
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Why is NGINX’s $request_uri empty?

24/03/2023

Resolved: How to convert Java bytecode to Webassembly using CheerpJ compiler

24/03/2023

Resolved: Is pandas groupby() function always produce a DataFrame with the same order respect to the column we group by?

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.