BackmediumLinked ListFlipkartCred

Monotonic Interval Partition Solution

Problem Statement

You are given the head of a singly‑linked list containing integer values. First verify that the list does not contain a cycle (use Floyd’s Tortoise‑and‑Hare algorithm). If a cycle is detected, the answer is false. Otherwise, determine whether there exists a node that can serve as a split point so that the list is divided into two non‑empty contiguous sub‑lists L1 and L2 satisfying both of the following conditions: (1) each sub‑list is monotonic – it is either entirely non‑decreasing or entirely non‑increasing; (2) the sum of the values in L1 equals the sum of the values in L2. Return true if such a split exists, otherwise return false. The split point may be any node except the first and last nodes of the original list.

Example 1
Input
head = [1, 2, 3, 3, 2, 1]
Output
true

Explanation: The list has no cycle. Splitting after the third element yields L1 = [1,2,3] (non‑decreasing) with sum 6 and L2 = [3,2,1] (non‑increasing) with sum 6. Both monotonicity and equal‑sum conditions are satisfied.

Example 2
Input
head = [5, 4, 4, 4, 5]
Output
false

Explanation: The list is acyclic. Any possible split creates at least one part that is not monotonic (e.g., splitting after the second element gives L1 = [5,4] which is decreasing, but L2 = [4,4,5] is not monotonic because it first stays flat then increases). Moreover, no split yields equal sums.

Example 3
Input
head = [2, 2, 2, 2]
Output
true

Explanation: The list is acyclic. Splitting after the second node gives L1 = [2,2] (both non‑decreasing and non‑increasing) with sum 4 and L2 = [2,2] with sum 4. Both parts are monotonic and their sums match.

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node.val <= 10^9
  • The list may be empty or contain a single node; in such cases return false because a split into two non‑empty parts is impossible.
  • Memory usage must be O(1) extra space besides the input list.
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

Monotonic Interval Partition — Problem Statement & Solution Guide

Linked ListMediumFloyd Cycle Detection
TimeO(n)
|
SpaceO(n)

Problem Description

You are given the head of a singly‑linked list containing integer values. First verify that the list does not contain a cycle (use Floyd’s Tortoise‑and‑Hare algorithm). If a cycle is detected, the answer is false. Otherwise, determine whether there exists a node that can serve as a split point so that the list is divided into two non‑empty contiguous sub‑lists L1 and L2 satisfying both of the following conditions: (1) each sub‑list is monotonic – it is either entirely non‑decreasing or entirely non‑increasing; (2) the sum of the values in L1 equals the sum of the values in L2. Return true if such a split exists, otherwise return false. The split point may be any node except the first and last nodes of the original list.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Monotonic Interval Partition"

medium

WHY DOES IT MATTER?

Detecting cycles and partitioning monotonic intervals are fundamental building blocks for data‑validation pipelines, stream processing, and memory‑safety checks. Mastery of these patterns prevents subtle bugs like infinite loops or incorrect segmentations in real‑time systems.

OPTIMIZATION CHALLENGE

The key insight is to decouple the two sub‑problems: first guarantee acyclicity, then transform the linked list into a random‑access view (an array) so that prefix‑suffix monotonicity can be computed in linear time. This eliminates the quadratic blow‑up of re‑scanning the list for every candidate split.

REAL-WORLD CONNECTION

Think of a network packet stream where each packet carries a timestamp. Verifying no cyclic routing (cycle detection) and then splitting the stream into an increasing‑time segment followed by a decreasing‑time segment mirrors load‑balancing decisions in distributed logging services.

During an interview, first write the cycle‑detection routine – it’s a quick win that shows you respect input constraints. Then, immediately store node values in a list; this small trade‑off of O(n) space lets you apply the powerful prefix‑suffix technique without getting tangled in pointer gymnastics.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(n)

Core Theory — Why This Approach?

The problem combines two classic linked‑list techniques: cycle detection with Floyd’s Tortoise‑and‑Hare and monotonic interval analysis. Floyd’s algorithm runs two pointers at different speeds; if they ever meet, a cycle exists, guaranteeing O(n) time and O(1) extra space. Once we know the list is acyclic, the remaining task is to find a split point that yields two contiguous sub‑lists each satisfying a monotonic property (e.g., non‑decreasing). A naïve solution would examine every possible split, recomputing monotonicity for each side, leading to O(n^2) time – infeasible for large n. The optimal paradigm is to pre‑compute prefix monotonic flags in a forward pass and suffix monotonic flags in a backward pass (by first materialising the list values into an array). With these two auxiliary boolean arrays, we can test every split in O(1) time, achieving overall O(n) time while using O(n) auxiliary space. This two‑pass, prefix‑suffix technique is a staple for interval‑partition problems across arrays and linked structures.

Interview Questions on This Problem

Q1How does Floyd’s Tortoise‑and‑Hare algorithm guarantee detection of a cycle in O(n) time without extra memory?

The hare moves two steps for every one step of the tortoise. If a cycle exists, the faster pointer will eventually lap the slower one inside the loop, causing them to meet. Because each pointer traverses at most 2n steps before meeting, the runtime is linear and no extra data structures are needed.

Q2Why can’t we determine the monotonic split point with a single forward pass on a singly‑linked list?

A single forward pass can only verify monotonicity of the prefix; to know whether the suffix (the remainder of the list) is monotonic we need information about the tail direction, which is only available after seeing the entire suffix. Without backward access or extra storage, we cannot evaluate all possible split points in O(1) per split.

Q3In a production system, how would you modify the algorithm to work in‑place without allocating an auxiliary array?

You could temporarily reverse the second half of the list after locating the midpoint, compute suffix monotonic flags while traversing the reversed half, then restore the original order. This yields O(1) extra space but adds constant‑factor overhead and requires careful pointer handling to avoid corrupting the list.

Examples

Example 1

Input

head = [1, 2, 3, 3, 2, 1]

Output

true

Explanation: The list has no cycle. Splitting after the third element yields L1 = [1,2,3] (non‑decreasing) with sum 6 and L2 = [3,2,1] (non‑increasing) with sum 6. Both monotonicity and equal‑sum conditions are satisfied.

Example 2

Input

head = [5, 4, 4, 4, 5]

Output

false

Explanation: The list is acyclic. Any possible split creates at least one part that is not monotonic (e.g., splitting after the second element gives L1 = [5,4] which is decreasing, but L2 = [4,4,5] is not monotonic because it first stays flat then increases). Moreover, no split yields equal sums.

Example 3

Input

head = [2, 2, 2, 2]

Output

true

Explanation: The list is acyclic. Splitting after the second node gives L1 = [2,2] (both non‑decreasing and non‑increasing) with sum 4 and L2 = [2,2] with sum 4. Both parts are monotonic and their sums match.

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node.val <= 10^9
  • The list may be empty or contain a single node; in such cases return false because a split into two non‑empty parts is impossible.
  • Memory usage must be O(1) extra space besides the input list.

Optimal Approach & Strategy

Detect cycles with Floyd, copy values to an array, compute prefix‑monotonic and suffix‑monotonic flags in two linear passes, then scan once to find a split where both flags are true.

Brute Force Approach

For each possible split, walk the left part to verify monotonicity and then walk the right part to verify monotonicity, repeating this for every node.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
   nums.sort((a, b) => a - b);
   let sum = nums.reduce((a, b) => a + b, 0);
   let target = Math.floor(sum / 2);
   let left = 0;
   let right = nums.length - 1;
   while (left < right) {
       let currentSum = nums[left] + nums[right];
       if (currentSum === target) {
           return currentSum;
       } else if (currentSum < target) {
           left++;
       } else {
           right--;
       }
   }
   return -1;
}

Asked in Top Tech Interviews

FlipkartCred

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.