🚀 How to Find Non-Overlapping Contiguous Subsequences That Sum to a Target in C#

PriyaPriya
4 min read

When working with data streams, logs, or financial time-series data, it's often important to detect continuous chunks of values that add up to a specific target. This C# solution is particularly useful when working with time-series arrays in .NET, or when building algorithmic tools that analyze contiguous data patterns.

In this post, we'll walk through a simple but powerful C# algorithm to find all non-overlapping contiguous subsequences of numbers in an array that sum up to a given target. This problem — also known as the contiguous subarray sum — shows up often in coding interviews and competitive platforms like HackerRank or LeetCode.


🧠 Problem Statement

🔹 Given an integer array nums[] and a target, find all non-overlapping contiguous subsequences (subarrays) whose sum equals the target.

Unlike subsets, we care about order and continuity — elements must be side-by-side in the original array.


🧪 Example

int[] nums = {1, 2, 3, 4, 7, 5, 5, 5, 5, 1000, 3, 3, 3, 1, 5, 6, 6, 4};

int target = 10;

✅ Output

{1,2,3,4}

{5,5}

{5,5}

{3,3,3,1}

Each printed group is a contiguous sequence (not just any subset) and no two sequences overlap.


💻 C# Code

Here’s the simple and readable C# solution:

using System;

using System.Collections.Generic;

class Program

{

static void Main()

{

int[] nums = {1, 2, 3, 4, 7, 5, 5, 5, 5, 1000, 3, 3, 3, 1, 5, 6, 6, 4};

int target = 10;

int i = 0;

while (i < nums.Length)

{

int sum = 0; // Start with a fresh sum

var sequence = new List<int>(); // Current contiguous sequence

int j = i;

while (j < nums.Length && sum < target)

{

sum += nums[j];

sequence.Add(nums[j]);

j++;

}

if (sum == target)

{

Console.WriteLine($"{{{string.Join(",", sequence)}}}"); // Clean string interpolation

i = j; // Move i to j to avoid overlap

}

else

{

i++; // Move to next starting point

}

}

}

}


🧮 Console Output

{1,2,3,4}

{5,5}

{5,5}

{3,3,3,1}

✅ Note: The output shows clean, non-overlapping sequences that exactly total to the target.


⚠️ Let’s Explore Some Edge Cases

Thinking beyond the happy path helps strengthen your solution. Here are some real-world scenarios to consider:

🔸 What if the array contains negative numbers?

  • This logic might skip valid sequences, because it stops early if sum >= target.

  • 💡 Tip: Remove sum < target in the while loop to explore the full range.

🔸 What if the target is zero?

  • Works fine! It will detect sequences like {0}, {-3, 3}, or {1, -1}.

🔸 What about sequences with just one element?

  • Already supported. If an element itself equals the target, it prints it.

🔸 Does it work with zeros?

  • Yes. Zeros are treated normally and can be part of valid sequences.

⚙️ Performance and Optimization

This is a brute-force approach — simple and effective for small to medium arrays.

💡 Want to go faster?
If your input contains only positive numbers, you can use a sliding window technique:

  • Expand the window while sum < target

  • Shrink it while sum > target

  • Record when sum == target

This reduces time complexity and is perfect for HackerRank, LeetCode, and other time-limited coding platforms.


🔍 Why This is HackerRank Friendly

This concept appears across multiple HackerRank sections:

  • Arrays → Subarray Division

  • Interview Prep Kit → Arrays

  • Algorithms → Search or Warm-Up

You’ll often see variants:

  • Allowing overlapping subarrays

  • Longest/shortest matching sequences

  • Maximum number of sequences

  • Sequences with constraints (odd/even only, fixed length, etc.)

By mastering this approach, you’ll unlock many pattern-matching and interval-based problems.


📈 Summary

✅ You learned how to:

  • Identify non-overlapping contiguous subarrays with a target sum

  • Write clean, modern C# code with interpolation

  • Think critically about edge cases

  • Prepare for similar HackerRank/LeetCode problems


💬 Wrapping Up

This is a small but mighty building block for anyone working with arrays, time-series data, or preparing for coding interviews.

💬 Have questions?

📩 Drop a comment — I'd love to help!

1
Subscribe to my newsletter

Read articles from Priya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Priya
Priya