How do I improve the efficiency of my JavaScript code to avoid surpassing the time limit on Leetcode?

I'm currently tackling the

Two Sum II - Input Array Is Sorted
problem on LeetCode, but I keep running into a Time Limit Exceeded issue. This indicates that my code isn't as optimized as it could be and may need a more efficient solution. However, optimizing code isn't my strong suit, so I'm specifically looking for guidance on how to eliminate two for-loops in my current code.

Question:

Two Sum II - Input Array Is Sorted

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, you need to find two numbers that add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2], where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are designed such that there is exactly one valid solution. You cannot use the same element twice. Your solution must only utilize constant extra space.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Hence, index1 = 1, index2 = 2. The function should return [1, 2].

Link to the question

My current code: Passing test cases 20 / 21

var twoSum = function(numbers, target) {
      let arr=[];
    for(let i=0; i<numbers.length; i++){
    let findNum= target - numbers[i];
        for(let j=i+1;j<numbers.length; j++){
           if(numbers[j]===findNum)
               arr.push(i+1, j+1);
        }
    }
    return arr
};

Any suggestions on how I can optimize my code to pass all test cases?

Answer №1

Providing a solution for Question 2 involves analyzing nested for loops. The inner loop will run n - i times, with i ranging from 1 to n. Therefore, the overall time complexity of the code is calculated as (n-1) + (n-2) + ... + 0, resulting in (n*(n-1))/2 and an O(n^2) solution. With n being 3 * 10^4, this would exceed 10^8 operations per second leading to a Time Limit Exceeded error. To address this issue, utilizing the properties of a sorted array can be effective. By employing two pointers—one at the start of the array and one at the end—we can approach the problem in three scenarios:

  1. If the sum of both pointer indices exceeds the target, decrement the last pointer index by 1.
  2. If the sum is less than the target, increment the first pointer by 1.
  3. If the sum equals the target, return the respective indices.

This process continues until the two pointers converge. Below is the complete code snippet.

    var twoSum = function(numbers, target) {
        let ans = [];
        while(i<j) {
            if(numbers[i] + numbers[j] > target) {
                j--;
            }
            else if(numbers[i] + numbers[j] < target) {
                i++;
            }
            else {
                ans.push(i+1);
                ans.push(j+1);
                break;
            }
        }
        return ans;
    };

Answer №2

Implementing the two-pointer strategy is a smart move,

  • Begin by setting left = 0 and right = length -1
  • Continue looping while left < right until you discover numbers[left] + numbers[right] === target

I prefer not to reveal the exact solution, as it would take away from the challenge.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to transform a raw readme file into an HTML formatted document using AngularJS, after retrieving it from GitHub

Can someone help me figure out how to format each line of the README.MD raw file into an HTML document using the controller below? angular.module('ExampleApp', []) .controller('ExampleController', function($scope, Slim,$sce) { ...

Using javascript to fetch JSON Objects

Struggling with fetching JSON objects and need help accessing the data within the "choices" key. Grateful for any guidance you can provide. ...

``Maneuvering through dynamically generated cells with multiple colsp

I'm currently working on creating a table using data from Vue.js. Depending on the value of a specific column, I want to split the cells into either 2 or 3 columns. Take a look at this image: The cell in row 01 and col 01 should be split into 3 vert ...

Tips for changing the value of a Django query set?

I have a query: def get_comment_tree(request): news_id = request.GET.get("news_id") ret = list(Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id", "user", "cre ...

Tips for populating a Flat List with nested JSON data in React-Native

As a beginner in React-Native and Javascript, I'm trying to figure out how to retrieve data for my FlatList. The JSON format I receive is structured like this: [ { "18": { "sellingUnitName": "unité(s)", "qualifier": "GOOD", " ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

Obtain headers from receiving an external JavaScript file

I am trying to find a way to import an external .js file and access the response headers from that request. <script src="external/file.js?onload=callback"> function callback(data) { data.getAllResponseHeaders(); } </script> Unfortunately, ...

Creating a flexible image layout within a container with relative positioning

I attempted to create a basic slideshow with images sliding from right to left as an animation: let slides = document.querySelectorAll('.img-container'); let l = slides.length; let i = 0; setInterval(function(){ i = (i + 1) % l; if(i == 0){ f ...

Discovering the Occurrences of each Object in a List using ReactJS

Struggling with arrays of objects in React.js. My list of objects looks like this : const list = [ { name: name1, age: age1, address: addresse1 }, { name: name2, age: age2, address: addresse2 }, { name: name1, age: age1, address: addresse4 }, { name ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

Retrieving CSS properties of an element using JavaScript

How can I efficiently retrieve all CSS rules associated with a specific element using JavaScript? I am not seeking a particular solution, just looking to capture all CSS rules for the given element. For example, consider the following HTML code: <div ...

Securely store object data using arrays of references to other objects

In my current PHP project, I have an object (actually a singleton, but that's not crucial). This particular object contains protected arrays with pointers to anywhere between ten and thirty other objects. I am looking for the easiest way to serialize ...

Json encode is not initialized

I am facing an issue with a simple ajax request that retrieves a json encoded array. The error message I keep receiving is that the response is not defined. I suspect I have misplaced the return statement in my function. Here is how the function looks: // ...

Adjusting the size of an image to be responsive once the document has fully

Struggling with creating a custom carousel/slider element and running into an issue that doesn't seem to make any sense. Attempting to retrieve image size using jQuery on document load results in incorrect width/height calculations. Initially thought ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

Exploring Navigation in AngularJS with ui-router

I've encountered an issue with ui-router functionality in my code. Here's a breakdown of the problem: Within my index.html file <li> <a ui-sref="day2">Day 2</a> </li> <li><a ui-sref="day3">Day 3</a& ...

Can anyone explain why I am having trouble loading JavaScript files into a different HTML file?

Currently, I am developing an electron application. In my index.html file, I have successfully loaded JavaScript files in the head tag and can access the JS functions without any problems. Now, I have created a separate browser window with another HTML fi ...

Switch the cursor to display the magnifying glass icon for zooming in and out

I am curious about how to modify the cursor shape to display a zoom in and zoom out symbol. Changing the cursor to indicate busy or wait status is something I am familiar with, document.manual_production.style.cursor='wait'; However, I am unsu ...

What is the best way to eliminate excessive spacing between two containers in mobile view?

I have created a layout with a single container and a row split into two columns. The left column contains a title and the right column contains a card, both centered. I am facing an issue when viewing it on mobile, there is excessive spacing between the t ...

Using logical operators in a loop to merge two separate datasets and form a new dataset in R

Looking to analyze two datasets, Mtest and Ztest, and compare the values in each set to zero in order to create a new dataset with the comparison results, leading to three possible outcomes. Result 1: Mtest > 0 & Ztest > 0 <- "OW" Result 2: Mtest ...