We will be discussing two methods to solve this;
one is using the sort() method.
Here in the above method the time complexity will be “O(nlogn)” due to sort() method. To make the time complexity better, the optimized code is given below.
This code above has only one for loop and hence the time complexity is O(n).