BackeasyStackZomatoTCS

Balanced Subsequence Sum Solution

Problem Statement

Balanced Subsequence Sum

You are given an array of integers. If the array contains an even number of elements, the answer is the sum of all elements. If the array contains an odd number of elements, sort the array in non‑decreasing order and add the two elements that occupy the middle positions of the sorted array. Return this sum.

Input: a single line containing the array elements separated by spaces. Output: a single integer representing the required sum.

Example 1
Input
4 -1 7 3
Output
13

Explanation: The array has 4 elements (even). Sum = 4 + (-1) + 7 + 3 = 13.

Example 2
Input
5 2 9
Output
14

Explanation: The array has 3 elements (odd). Sorted array: 2 5 9. Middle positions are 5 and 9. Sum = 5 + 9 = 14.

Example 3
Input
10 -3 7 4 1
Output
11

Explanation: The array has 5 elements (odd). Sorted array: -3 1 4 7 10. Middle positions are 4 and 7. Sum = 4 + 7 = 11.

Constraints

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • The result fits in a 64‑bit signed integer
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Balanced Subsequence Sum — Problem Statement & Solution Guide

StackEasyNext Greater Element
TimeO(n) expected (or O(n log n) worst‑case with full sort)
|
SpaceO(1) extra

Problem Description

Balanced Subsequence Sum

You are given an array of integers. If the array contains an even number of elements, the answer is the sum of all elements. If the array contains an odd number of elements, sort the array in non‑decreasing order and add the two elements that occupy the middle positions of the sorted array. Return this sum.

Input: a single line containing the array elements separated by spaces.

Output: a single integer representing the required sum.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Balanced Subsequence Sum"

easy

WHY DOES IT MATTER?

Identifying and extracting a small subset of order statistics (the middle elements) is a recurring pattern in interview problems, teaching candidates to avoid unnecessary full sorts and to think in terms of selection algorithms.

OPTIMIZATION CHALLENGE

The key insight is that only two elements matter when the length is odd, so you can replace a full O(n log n) sort with a linear‑time selection (QuickSelect) or a partial sort that stops after extracting the required middle window.

REAL-WORLD CONNECTION

In distributed systems, aggregating median or percentile metrics from massive logs mirrors this pattern: you need only the central values for performance dashboards, not the entire sorted dataset.

During an interview, first check the array size parity; if even, compute the sum on the fly. For odd sizes, quickly decide whether a full sort is acceptable given constraints, otherwise fall back to QuickSelect to keep the solution both fast and memory‑efficient.

COMPLEXITY AT A GLANCE

⏱ Time:O(n) expected (or O(n log n) worst‑case with full sort)
💾 Space:O(1) extra

Core Theory — Why This Approach?

The problem reduces to two distinct cases based on the parity of the input size. When the array length is even, the answer is simply the arithmetic sum of all elements, which can be obtained in linear time by a single traversal. When the length is odd, the challenge is to identify the two elements that lie in the middle of the sorted order. A naive approach would sort the entire array, which costs O(n log n) time, but this is optimal for the general case because locating the k‑th and (k+1)-th order statistics without full sorting still requires linear time on average. The optimal paradigm therefore combines a linear scan for the even case and a selection‑or‑sorting step for the odd case, leveraging the fact that only two order statistics are needed, not the full ordering.

Naïve solutions that repeatedly sort for each query or that recompute sums after each insertion become prohibitive for large inputs, leading to O(n^2) or higher complexities. By recognizing that the problem only asks for a constant‑size summary (either the total sum or two middle values), we can apply either a single pass accumulation or a linear‑time selection algorithm (e.g., QuickSelect) to achieve O(n) time for the odd case, while keeping auxiliary space to O(1) if we operate in‑place. This demonstrates the classic trade‑off between full sorting and targeted selection, a core concept in algorithm design.

The optimal solution thus follows a simple decision tree: check parity, compute sum directly if even, otherwise find the two middle elements via sorting or selection and add them. This yields a deterministic O(n log n) worst‑case bound (or O(n) expected with QuickSelect) and constant extra space, satisfying both time and memory constraints for typical interview constraints.

Interview Questions on This Problem

Q1How would you modify the solution if the array could contain up to 10^7 elements and memory usage must stay below 100 MB?

Use an in‑place QuickSelect to find the two middle order statistics in O(n) expected time, avoiding a full sort. Accumulate the total sum in the same pass for the even case, and keep only a few variables, ensuring O(1) extra space.

Q2Can you extend the problem to return the sum of the k middle elements for any odd k? What changes in the algorithm?

For a general odd k, you need to locate the (n‑k)/2‑th to (n+k)/2‑th order statistics. This can be done by partially sorting using nth_element (or QuickSelect repeatedly) to isolate the required window in O(n) expected time, then sum those k elements.

Q3Why is it safe to ignore overflow concerns in most interview settings for this problem, and how would you handle it in production code?

Interviewers typically assume inputs fit within 32‑bit or 64‑bit integers, focusing on algorithmic insight. In production, you would use a larger integer type (e.g., long long in C++ or BigInteger in Java) or check for overflow before addition, especially when summing large arrays.

Examples

Example 1

Input

4 -1 7 3

Output

13

Explanation: The array has 4 elements (even). Sum = 4 + (-1) + 7 + 3 = 13.

Example 2

Input

5 2 9

Output

14

Explanation: The array has 3 elements (odd). Sorted array: 2 5 9. Middle positions are 5 and 9. Sum = 5 + 9 = 14.

Example 3

Input

10 -3 7 4 1

Output

11

Explanation: The array has 5 elements (odd). Sorted array: -3 1 4 7 10. Middle positions are 4 and 7. Sum = 4 + 7 = 11.

Constraints

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • The result fits in a 64‑bit signed integer

Optimal Approach & Strategy

If the length is even, compute the sum in one pass; if odd, use QuickSelect or nth_element to find the two middle order statistics in linear time and sum them.

Brute Force Approach

Sort the entire array regardless of size and then either sum all elements (even) or add the two middle elements (odd).

Verified Code Solutions

JavaScript Solution
Time: O(n) expected (or O(n log n) worst‑case with full sort)
function solution(nums) {
   if (nums.length < 2) return 0;
   if (nums.length % 2 === 0) return nums.reduce((a, b) => a + b, 0);
   return Math.max(nums[nums.length / 2 - 1], nums[nums.length / 2]);
}

Asked in Top Tech Interviews

ZomatoTCS

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.