A different and more efficient way to address the issue at hand

During a recent interview, I was asked the following question and despite being able to solve it, the interviewer pointed out that my code was not optimized. Is there anyone who can help me with an optimized solution?

Question : Given an array array1, rearrange the array in the format:

  1. All negative numbers and their absolute values should be inserted first in the array (sorted).
  2. The remaining items should be concatenated to the new array (sorted).
//input 
var array = [8,7,0,6,4,-9,-7,2,-1,3,5,1,10];
//output
var array2 = [-7,7,-1,1,-9,0,2,3,4,5,6,8,10];

My Code :

function sort(arr){  
  var arrange = arr.sort((a, b)=>{ return a-b});
  var array1=[];
  for(let i=0; i<arrange.length; i++){
    let firstItem = Math.abs(arrange[i]);
    for(let j=i+1; j<arrange.length; j++){
       if(firstItem === Math.abs(arrange[j])){
         array1.push(arrange[i], arrange[j])       
       }
   }
  }
  arrange = arrange.filter((item, i)=>{
     return array1.indexOf(item) === -1
  })
 return [...array1, ...arrange]
} 


console.log(sort(array));

JSBIN

Please give some hints also, what is wrong with my approach.

Note : The code I wrote has a time complexity of o(n^2), but the interviewer wanted a O(log n) solution without nested for loops. Can we achieve this?

Answer №1

This particular approach may not be the most efficient as it consumes more processing time due to complexities like sorting and filtering, resulting in a complexity of O(n^2). This means that as the number of elements increases, the time taken also increases.

When faced with such questions, it is advisable to avoid using nested loops if feasible.

Answer №2

It appears that there are several issues with your algorithm.

  1. The nested for loops have a time complexity of O(n2).
for(let i=0; i<arrange.length; i++){ // ----------O(n)
  let firstItem = Math.abs(arrange[i]);
  for(let j=i+1; j<arrange.length; j++){ // ---------x O(n(n+1)/2)==O(n^2)
       if(firstItem === Math.abs(arrange[j])){
         array1.push(arrange[i], arrange[j])       
       }
   }
}
  1. The use of filter + indexOf both result in O(n2) complexity as well.
arrange = arrange.filter((item, i)=>{ // O(n)
   return array1.indexOf(item) === -1 // -- x O(n*n) // because indexOf is O(n)
})

A potential solution could involve optimizing the algorithm to run in O(nlog(n)).

One approach could be:

  • Identify negative numbers along with their corresponding positive counterparts using a map
  • Separate out the positive numbers into another container
  • Sort the negative map based on keys
  • Output the negative map and remove any associated positives from the positive container
  • Sort the positive container and output it
... (continue with the rest of the text) What I want to highlight is that while incremental optimizations can improve performance, focusing on algorithm efficiency and data structure choices play a more significant role in achieving optimal results.

Answer №3

Presented below is an alternative approach

//input 
var array = [8,7,0,6,4,-9,-7,2,-1,3,5,1,10];
//output
var array2 = [-7,7,-1,1,-9,0,2,3,4,5,6,8,10];


console.clear();

function sort(arr){
  const singular=[];
  const arrange = arr.sort((a, b)=>{ return a-b});

  const output = arrange.flatMap((item, i)=>{
     if(item < 0 && arrange.includes(-item)){
         return [item, -item];       
     }else{
       singular.push(item);
     }     
  }).filter((item)=>{ return item; });

  const result = [...new Set(output), ...singular];

  console.log('result : ', result);
} 


console.log(sort(array));

Answer №4

Your approach includes 2 sorts and a nested for loop, which may not be the most efficient solution from a business standpoint.

The complexity of sorting is O(nlog(n)), while a nested for loop has a complexity of O(n^2).

When tackling problems with arrays, it's worth considering linear solutions first before resorting to sorting. Sorting is necessary in this case, but using nested loops should be avoided unless absolutely required - it comes with added responsibilities!

Take a look at the following solution, which utilizes one sort and iterates through the array twice:

function modifyArray(array) {
    var sorted = array.sort((a, b) => { return a - b });
    let map = {};
    for (var i = 0; i < sorted.length; i++) {
        map[sorted[i]] = true;
    }

    let negativesAndAbsolutes = [];
    let uniqueNegatives = [];
    let uniquePositives = [];
    let currNumber = null;

    for (var i = 0; i < sorted.length; i++) {
        currNumber = sorted[i];
        if (!map[currNumber]) {
            // already sorted.
            continue;
        }
        if (currNumber < 0) {
            if (map[-1 * currNumber]) {
                // negative number with its absolute value present.
                negativesAndAbsolutes.push(currNumber, -1 * currNumber);
                map[currNumber] = false;
                map[-1 * currNumber] = false;       // don't process it again.
                continue;
            } else {
                // unique negative.
                uniqueNegatives.push(currNumber);
            }
            continue;
        }
        uniquePositives.push(currNumber);
    }

    return [...negativesAndAbsolutes, ...uniqueNegatives, ...uniquePositives];
}

modifyArray([8,7,0,6,4,-9,-7,2,-1,3,5,1,10]);

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

Can we separate city, state, and country data into individual input fields using Autocomplete and Geonames?

Currently, I have a single INPUT field set up to trigger the jQuery UI Autocomplete function, which pulls data from Geonames API. $( "#city_state_country" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "http ...

Two interactive dropdown menus featuring custom data attributes, each influencing the options available in the other

Looking to create interactive select boxes based on the data attribute values? This is the code I currently have: HTML <select id="hours" onchange="giveSelection()"> <option value="somethingA" data-option="1">optionA</option> <o ...

Troubleshooting: Unable to load template file content in AngularJS ng-view

Setting up a demo angular app has been quite the challenge for me. Despite my efforts, the content from my partial file (partials/test.html) is not loading into the layout file as expected. Below is a snippet of my index.html: <!DOCTYPE html> <ht ...

What could be causing my cmd to report an error stating that it is unable to locate the node-modules

https://i.sstatic.net/4ztfB.png Take a look at my command prompt below. Do I need to keep the module folder and the code folder in the same directory? ...

What is the best way to monitor a document variable that is set after a component has been

Is there a way to access the variable document.googleAnalytics, added by Google Tag Manager, for A/B testing on a Vue.js page? I attempted to initialize the variable in both the mounted and created methods of the component, but it returns as undefined: ex ...

Displaying a div after a successful form submission using Jquery

I created two popup windows. One is used to ask the user whether they want to submit the form, and if they click 'yes', the form is submitted. The issue I encountered is that the other popup window should be shown after the form is successfully s ...

Enhance the material-table component by incorporating dynamic information into the lookup property

I am currently facing challenges while attempting to dynamically add data to the lookup property in the Material-Table component. The lookup is structured as an object, and you can refer to its definition in the initial example provided here. However, it ...

Angular's Conditional ng-if Error

Encountering an error link from Angular Js [1]http://errors.angularjs.org/1.2.10/$parse/lexerr?p0=Unterminated%20quote&p1=s%2013-14%20%5B'%5D&p2=recipe.ID%20!%3D%3D' I am struggling to implement the solution for this error. Any help wou ...

Compatibility Issue between Jquery UI CheckBox Button and Click Function in IE8

Situation: After calling addButton() function in jQuery, the checkbox element is successfully turning into a button. However, the click event that should trigger an alert message is not functioning. This issue seems to be specific to IE-8 compatibility. ...

What's the best way to save data from an HTML input field into a JavaScript array?

Can someone help me with storing a value from an HTML input field into a JavaScript array after a button click, and then displaying that array data on the screen? Here is the HTML code I am currently working with: <!DOCTYPE HTML> <html> < ...

The tooltip in a scrollable container of Highcharts moves along with the content as it scrolls

I am currently facing an issue with my Highcharts instance that is displayed within a scrollable container. In addition, I have set the tooltip.outside option to true so that the tooltip always appears on top even if it exceeds the chart svg. The problem ...

A guide on updating an item in a basic JavaScript file with Node.js

This query pertains to Workbox and Webpack, but no prior knowledge of these libraries is necessary. Background Information (Optional) Currently using the InjectManifest plugin from Workbox 4.3.1 (workbox-webpack-plugin). While this version provides the o ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

Incorporating JavaScript to dynamically load an HTML page into an iframe

I am attempting to have each option load a unique page within a frame <!DOCTYPE html> <html> <head> <script> function selectCountry() { var mylist=document.getElementById("country"); document.getElementById("frame").src=mylist.opti ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

Is it possible to define a 2-D array using the ref( ) function in VueJS?

I'm looking to dynamically create a 2-D array that allows the number of rows in the first dimension to increase when clicking on a designated button. <script setup> ... // When defining the table as follows: var tab=ref([]) // This function is e ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

Populating a textbox with a portion of my PHP array

I've got this JSON file with variable content. Here's an example link to it: The JSON data looks something like this: { "status": "ok", "total": 4, "results": { "distance": [...], "lng": [...], "lat": [...], "fourpp": [ ...

What are some techniques for preventing Null Pointer Exception errors?

Currently, I am working on a project that involves creating a form with a dropdown field for categories. Based on the chosen category, I need to populate a second dropdown called subcaste using AJAX. To achieve this, I have implemented a method that disab ...