14 November 2023
By: ThinkingFunctionally

1877 Minimize Maximum Pair Sum in Array

(defn min-pair-sum [nums]
  (let [sorted-nums (sort nums)
        n (count sorted-nums)]
    (loop [i 0
           j (dec n)
           m 0]
      (if (< i j)
        (recur (inc i)
               (dec j)
               (max m (+ (nth sorted-nums i) (nth sorted-nums j))))
        m))))

(def nums [3 5 2 3])
(println (min-pair-sum nums))

Certainly! Let's break down the time and space complexity analysis for the given code snippet:

Time Complexity Analysis:

  1. Sorting the input vector nums using the sort function takes O(n log n) time, where n is the length of the vector.
  2. The count function is used to determine the length of the sorted vector, which takes O(1) time.
  3. The loop iterates from the start and end of the sorted vector towards the center. The number of iterations in the loop is approximately n/2, where n is the length of the input vector.
  4. Inside the loop, the operations of incrementing i, decrementing j, comparing i and j using <, and calculating the maximum pair sum using max and addition take constant time O(1).
  5. As a result, the overall time complexity is dominated by the sorting operation, resulting in O(n log n) time complexity.

Space Complexity Analysis:

  1. The space complexity is determined by the auxiliary space used for sorting the input vector. In this case, the sorted-nums vector is created, which requires additional space of O(n), where n is the length of the input vector.
  2. The n variable holds the length of the sorted vector and requires constant space O(1).
  3. The loop variables i, j, and m are used to keep track of the loop state and require constant space O(1).
  4. Therefore, the overall space complexity is O(n).

In summary, the time complexity of the min-pair-sum function is O(n log n), and the space complexity is O(n), where n is the length of the input vector nums.

Tags: Leet Code