Largest K such that both K and -K exist in array, Is my solution O(n+logn) or O(nlogn)
/**
 * Write a function that, given an array A of N integers, returns the lagest integer K > 0 such that both values K and -K exist in array A. If there is no such integer, the function should return 0.
 * 
Input: [3, 2, -2, 5, -3]
Output: 3

Input: [1, 2, 3, -4]
Output: 0
 */


/**
 * Time: O(n+logn) = O(n), logn to sort the list and n to iterate through the list once
 * Space: O(n) to store the sorted list
 */
function largestInt(list){
  if (list.length < 2) return 0;
  
  const sorted = list.sort((a,b) => b - a);
  let left = 0, right = list.length - 1;
  while (left < right){
    if (list[left] < 0 || list[right] > 0) return 0;
    const rightPositive = Math.sqrt(sorted[right]**2);
    if (list[left] === rightPositive) return list[left];

    if (list[left] > rightPositive) left++;
    else right--; 
  }
  return 0;
}

I think that should be O(n+logn) since we sort it once which has O(n+logn) = O(n) time complexity and then we iterate through once. But from discussions, online folks are suggesting it is O(nlogn). Could someone help me understand whether I'm wrong here?

Comments (1)