ZeroToSky
Data Structures and Algorithms Tutorial 13 of 486
Foundations 17/41
Fundamentals

All 13 lessons →

Maths, Pattern & Recursion

All 28 lessons →

Core Data Structures 0/224
Array & String
  • Array Basics
  • String Basics
  • Matrix Basics
  • Is Sorted
  • Multiply with Adjacent
  • Reverse Array
  • Reverse in Groups
  • Rotate Array
  • Generate All Subarrays
  • Arrange by Sign
  • Stock Buy/Sell - One Transaction
  • Stock Buy/Sell - Multiple Transactions
  • Leaders in Array
  • Same Strings
  • Palindrome String
  • Toggle Case
  • Remove Occurrences
  • Remove Spaces
  • Check Subsequence
  • First Non-Repeating Character
  • Pangram
  • Majority Element
  • Majority Element II
  • Sorted Subsequence of 3
  • Count Strictly Increasing Subarrays
  • Next Permutation
  • Kadane's Algorithm
  • Sum of All Subarrays
  • Maximum Product Subarray
  • Implement atoi
  • URLify
  • Multiply Large Numbers
  • Diagonal Traversal
  • Magic Square
  • Boundary Traversal
  • Spiral Matrix
  • Toeplitz Matrix
  • Matrix Zig-Zag
  • Transpose of Matrix
  • Rotate Matrix by 90 Degrees
  • Conway's Game of Life
  • Queries in a Matrix
  • Set Matrix Zeroes
  • Maximum Circular Subarray Sum
  • Next Smallest Palindrome
  • Lexicographic Rank
  • Text Justification

All 47 lessons →

Linked List
  • Linked List Basics
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Reverse Singly Linked List
  • Reverse Doubly Linked List
  • Reverse in Groups
  • Reorder List
  • Find Middle
  • Remove Nth From End
  • Check Palindrome
  • Detect Cycle
  • Intersection of Y-Shaped Lists
  • Sort 0s 1s 2s
  • Add Two Numbers
  • Merge K Sorted Lists
  • Browser History
  • Twitter Design
  • LRU Cache
  • LFU Cache
  • Flatten Linked List
  • Clone Linked List With Random Pointer

All 22 lessons →

Stack
  • Stack Basics
  • Reverse Stack
  • Sort Stack
  • Balanced Parentheses
  • Postfix Evaluation
  • Infix Evaluation
  • Infix to Postfix
  • Redundant Brackets
  • Longest Valid Parentheses
  • Stack Using Queues
  • Two Stacks in an Array
  • K Stacks in an Array
  • Stack With getMin
  • Remove K Digits
  • Next Greater Element
  • Stock Span Problem
  • Previous Smaller Element
  • Largest Rectangle in Histogram
  • Trapping Rain Water
  • Decode String

All 20 lessons →

Queue
  • Queue Basics
  • Circular Queue
  • Queue Using Stacks
  • FIFO Page Replacement
  • Reverse a Queue
  • Reverse First K Elements
  • Interleave Queue
  • K Queues in an Array
  • First Non-Repeating Character in a Stream
  • Minimum Knight Steps

All 10 lessons →

Deque
  • Deque Basics
  • Circular Array Implementation
  • Lexicographically Largest Permutation
  • Generate Bitonic Sequence
  • Sliding Window Maximum
  • Longest Subarray With Difference <= X
  • Minimum Deques to Sort Array

All 7 lessons →

Hashing
  • Hashing Basics
  • Linear Probing
  • Separate Chaining
  • Quadratic Probing
  • Distinct in Array
  • Is Subset
  • Union of Arrays
  • Intersection of Arrays
  • Two Sum
  • Fizz Buzz
  • Pair Sums Divisible by K
  • Roman to Integer
  • Isomorphic Strings
  • Count Frequencies
  • Most Frequent Element
  • Maximum Subsets
  • Anagrams
  • Longest Consecutive Subsequence
  • Consecutive Subsequence

All 19 lessons →

Heap
  • Heap Basics
  • Check for Heap
  • Heap Sort
  • Kth Largest
  • K Largest Elements
  • Height of Heap
  • Connect N Ropes
  • Nearly Sorted Array
  • BST to Min Heap
  • K Max Sum Combinations
  • Median in a Stream
  • Kth Largest in a Stream
  • Merge K Sorted Arrays/Lists
  • Range Covering K Sorted Lists
  • Skyline Problem
  • Sort by Frequency

All 16 lessons →

Binary Tree
  • Binary Tree Basics
  • Inorder Traversal
  • Preorder Traversal
  • Postorder Traversal
  • Level Order Traversal
  • Size of Tree
  • Depth of Tree
  • Maximum Width
  • Check Balanced Tree
  • Identical Trees
  • Mirror Tree
  • Sum Tree
  • Left View
  • Right View
  • Path Sum
  • Maximum Path Sum
  • Serialize and Deserialize
  • Iterative Inorder
  • Iterative Preorder
  • Iterative Postorder
  • Morris Inorder
  • Diameter of Tree
  • Boundary Traversal
  • Tree From Preorder and Inorder
  • Connect Nodes at Same Level
  • Invert Tree
  • Flatten Tree
  • Vertical Traversal
  • Bottom View
  • Top View
  • Spiral Level Order
  • Lowest Common Ancestor
  • Distance K
  • Subtree Check

All 34 lessons →

Binary Search Tree
  • BST Basics
  • Search in BST
  • Insert in BST
  • Delete in BST
  • Ceil in BST
  • Floor in BST
  • Predecessor and Successor
  • Kth Smallest Element
  • Two Sum in BST
  • Sorted Array to BST
  • Merge Two BSTs
  • Validate BST
  • Lowest Common Ancestor
  • Recover BST
  • Largest BST Subtree

All 15 lessons →

Trie
  • Implement Trie
  • Longest Word With All Prefixes
  • Count Distinct Substrings
  • Maximum XOR of Two Numbers
  • Maximum XOR Queries
  • Pairs With XOR Less Than K
  • Search Suggestions System
  • Palindrome Pairs

All 8 lessons →

Graph
  • Graph Representation
  • BFS Traversal
  • DFS Traversal
  • Flood Fill
  • Number of Islands
  • Connected Components in Undirected Graph
  • Cycle in Undirected Graph
  • Cycle in Directed Graph
  • Bipartite Graph
  • Rotten Oranges
  • Topological Sort
  • Course Schedule I
  • Course Schedule II
  • Alien Dictionary
  • Dijkstra's Algorithm
  • Floyd Warshall
  • Bellman-Ford
  • Minimum Cost Path
  • Shortest Cycle in Undirected Graph
  • Distance of Nearest 1
  • Word Ladder
  • Prim's Algorithm
  • Disjoint Set Union
  • Kruskal's Algorithm
  • Detect Cycle Using DSU
  • Number of Connected Components

All 26 lessons →

Problem-Solving Patterns 0/99
Two-Pointer
  • Two-Pointer Technique
  • Two Sum in Sorted Array
  • Smallest Subarray
  • Unique Elements
  • Sentence Palindrome
  • Three Sum
  • Celebrity Problem
  • Closest Pair from Two Arrays
  • Container With Most Water
  • Common Elements in Three Arrays
  • Reverse Words
  • Four Sum
  • Closest Triplet
  • Count Triplets

All 14 lessons →

Sliding Window
  • Sliding Window Technique
  • Maximum Sum Subarray of Size K
  • Maximum XOR of K Size
  • Distinct in Every Window
  • MEX of Subarrays
  • Minimum Swaps to Group All 1s
  • First Negative in Every Window
  • Chocolate Distribution
  • Maximize Ones
  • Equal Substring With Cost <= K
  • Fruit Into Baskets
  • Subarray With Given Sum
  • Smallest Subarray With Sum Greater Than X
  • Minimum Window Subsequence
  • Minimum Window Substring
  • Subarrays With K Odds
  • Subarrays Less Than K
  • Longest Substring With Distinct Characters
  • Longest Substring With K Unique Characters
  • Count Anagrams

All 20 lessons →

Prefix Sum
  • Prefix Sum Basics
  • Prefix Sum Array
  • 2D Prefix Sum
  • Range Queries
  • Equilibrium Index
  • Product of Array Except Self
  • Difference Array
  • 2D Difference Array
  • Subarray With Zero Sum
  • Largest Subarray With Zero Sum
  • Largest Subarray With Equal 0s and 1s
  • Longest Subarray With Sum K
  • Count Subarrays With Sum K
  • Count Subarrays With Given XOR

All 14 lessons →

Bit Manipulation
  • Bit Manipulation Basics
  • Swap Without Third Variable
  • Kth Set Bit
  • Only Set Bit
  • Power of Two
  • Sort by Set Bits
  • Power of Four
  • Binary Palindrome
  • Rotate Bits
  • Swap Odd and Even Bits
  • Count Set Bits
  • Count Total Set Bits
  • Maximum Consecutive 1s
  • Missing Number
  • One Odd Occurring
  • Two Odd Occurring
  • Missing and Repeating
  • Unique Numbers II
  • Gray Codes
  • Hamming Distance
  • Sum of Pair XORs
  • Sum of Subset XORs
  • Subarray XORs
  • Subsets
  • Subsequences

All 25 lessons →

Backtracking
  • Backtracking Basics
  • Permutations
  • Rat in a Maze
  • Word Search
  • N-Queen Problem
  • Sudoku Solver
  • Word Break
  • Knight's Tour
  • Palindromic Partitions
  • M-Coloring

All 10 lessons →

Greedy
  • Greedy Algorithm Basics
  • Fractional Knapsack
  • Assign Cookies
  • Smallest Subset With Greater Sum
  • Minimum Notes With Given Sum
  • Activity Selection
  • Huffman Coding
  • Jump Game
  • Job Sequencing
  • Non-Overlapping Intervals
  • Gas Station
  • Stable Marriage
  • Minimize Maximum Height Difference
  • No Two Adjacent Same
  • Minimize Cash Flow
  • Min Time to Finish Jobs With Constraints

All 16 lessons →

Core Algorithms 0/122
Searching
  • Searching Basics
  • Largest Element
  • Second Largest
  • Local Min and Max
  • Search Insert Position
  • Lower Bound
  • Upper Bound
  • Single Element in Sorted Array
  • Missing Natural Number
  • Count Occurrences
  • Search in 2D Matrix
  • Search in Sorted and Rotated Array
  • Search in Sorted and Rotated Array II
  • K Closest Elements
  • Search in Almost Sorted Array
  • Peak Element
  • Peak Element in 2D
  • Range Based Counts
  • Kth Missing Positive
  • Search in Row-Column Sorted Matrix
  • Square Root
  • Nth Root
  • Check Power
  • Book Allocation
  • Koko Eating Bananas
  • Aggressive Cows
  • Median in Row Sorted Matrix
  • Kth Smallest in Row and Column Sorted Matrix
  • M Bouquets
  • Kth in Multiplication Table
  • Median of Two Sorted Arrays
  • Kth Element of Two Sorted Arrays

All 32 lessons →

Sorting
  • Sorting Basics
  • Wave Form
  • Sort by Length
  • Minimum Difference Pair
  • Merge Overlapping Intervals
  • Form Largest Number
  • Meeting Rooms
  • Insert and Merge Intervals
  • Minimize Moves
  • Quick Sort
  • Sort Binary Array
  • Move Zeroes to End
  • Sort Ternary Array
  • Merge Sort
  • Union of Two Sorted Arrays
  • Intersection of Two Sorted Arrays
  • Merge Without Extra Space
  • Minimum Platforms
  • Inversion Count
  • Cycle Sort
  • Minimum Missing Positive
  • Minimum Swaps to Sort

All 22 lessons →

Dynamic Programming
  • Dynamic Programming Basics
  • Climbing Stairs
  • Count Without Consecutive 1s
  • Frog Jump
  • House Robber
  • Maximum Segments
  • Coin Change
  • Decode Ways
  • Word Break
  • Unique Paths
  • Minimum Cost Path
  • Longest Common Subsequence
  • Edit Distance
  • Distinct Subsequences
  • Largest Square Submatrix of 1s
  • Partition Equal Subset Sum
  • Subset Sum
  • Count Subsets With Given Sum
  • Target Sum
  • 0/1 Knapsack
  • Coin Change II
  • Rod Cutting
  • Unique Paths in a Grid
  • Maximum Path Sum in Matrix
  • Longest Increasing Path
  • Longest Common Substring
  • Shortest Common Supersequence
  • Interleaving String
  • Wildcard Matching
  • Longest Palindromic Substring
  • Buy/Sell With Cooldown
  • Buy/Sell With At Most Two Transactions
  • Buy/Sell With K Transactions
  • Buy/Sell With Transaction Fee
  • Longest Increasing Subsequence
  • Number of LIS
  • Longest Bitonic Subsequence
  • Longest String Chain
  • Matrix Chain Multiplication
  • Minimum Cost to Cut a Stick
  • Palindrome Partitioning
  • Boolean Parenthesization
  • Partition Array for Maximum Sum
  • Egg Dropping

All 44 lessons →

String Matching
  • Substring Search
  • Rabin-Karp
  • KMP Algorithm
  • Z Algorithm
  • Longest Prefix Suffix
  • Manacher's Algorithm
  • Longest Palindromic Substring
  • Palindrome Substring Queries
  • Minimum Repeats for Substring

All 9 lessons →

Number Theory
  • nCr
  • Euler's Totient
  • Sieve of Eratosthenes
  • Pascal's Triangle
  • Modular Exponentiation
  • Segmented Sieve

All 6 lessons →

Range Query
  • Segment Tree
  • Min-Max Range Queries
  • Range LCM Queries
  • Range XOR Queries
  • Lazy Propagation
  • Flipping Sign
  • Segment Tree on N-ary Rooted Tree
  • Fenwick Tree
  • Sum and Update Queries on 3D Matrix

All 9 lessons →

DSA Input and Output: Read, Process and Print Data

Learn how programming problems accept input, process data, and produce output. This beginner-friendly DSA tutorial covers common input/output patterns with examples in C#, Python, Java, and C++.

Gaurav 5 min read Sign in to save
On this page

DSA Input and Output: Read, Process and Print Data

Input and output are the foundation of solving Data Structures and Algorithms (DSA) problems.

Before learning arrays, strings, linked lists, trees, graphs, or dynamic programming, you should understand how to:

  1. Read input from the user or an online judge.
  2. Convert input into the required data type.
  3. Store input in variables or data structures.
  4. Process the data.
  5. Print the expected output.

Most coding platforms provide input in a predefined format. Your job is to read that input correctly, solve the problem, and produce exactly the required output.


1. What Are Input and Output?

Consider a simple problem:

Given two integers, print their sum.

Input

10 20

Output

30

The complete flow is:

Input → Processing → Output
 10,20 → 10 + 20 → 30

This simple pattern appears in almost every DSA problem.


2. Why Input and Output Matter in DSA

When solving problems on platforms such as coding judges, the platform usually provides the input automatically.

For example:

5
10 20 30 40 50

Here:

  • 5 represents the number of elements.
  • The next line contains the array elements.

Your program must understand this structure.

A small input-reading mistake can cause your otherwise correct algorithm to fail.

Common problems include:

  • Reading the wrong number of values.
  • Treating a number as a string.
  • Reading only one value when multiple values are present.
  • Ignoring extra spaces or new lines.
  • Printing additional text when the judge expects only the answer.

3. Basic Input and Output in C#

Since C# is widely used in professional development and competitive programming, let's start with C#.

Reading a Single Integer

int n = int.Parse(Console.ReadLine());

If the input is:

25

Then:

n = 25

Reading a String

string name = Console.ReadLine();

Input:

Gaurav

Output:

Console.WriteLine(name);

Result:

Gaurav

Reading a Double

double price = double.Parse(Console.ReadLine());

4. Reading Multiple Values on One Line

Suppose the input is:

10 20

We want to store the two numbers in a and b.

string[] input = Console.ReadLine().Split();

int a = int.Parse(input[0]);
int b = int.Parse(input[1]);

Console.WriteLine(a + b);

Output:

30

How does it work?

The statement:

Console.ReadLine()

reads:

10 20

Then:

.Split()

separates the values:

["10", "20"]

Finally:

int.Parse()

converts strings into integers.


5. A Better C# Pattern for Multiple Integers

For DSA problems, you will frequently need to convert several values.

You can use:

int[] values = Console.ReadLine()
    .Split()
    .Select(int.Parse)
    .ToArray();

For input:

10 20 30 40

The resulting array is:

[10, 20, 30, 40]

Then:

Console.WriteLine(values[0]);

prints:

10

6. Reading an Array

Suppose the problem gives:

5
10 20 30 40 50

The first line represents the number of elements.

int n = int.Parse(Console.ReadLine());

int[] arr = Console.ReadLine()
    .Split()
    .Select(int.Parse)
    .ToArray();

Now:

n = 5
arr = [10, 20, 30, 40, 50]

We can access elements using indexes:

Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);

Output:

10
20

Remember that array indexing starts from 0.

Index:  0   1   2   3   4
Value: 10  20  30  40  50

7. Printing an Array

You can use a loop:

for (int i = 0; i < arr.Length; i++)
{
    Console.Write(arr[i] + " ");
}

Output:

10 20 30 40 50

You can also use:

Console.WriteLine(string.Join(" ", arr));

Output:

10 20 30 40 50

8. Console.Write vs Console.WriteLine

These two methods are commonly used in DSA.

Console.Write

Does not automatically move to the next line.

Console.Write(10);
Console.Write(20);

Output:

1020

Console.WriteLine

Moves to the next line after printing.

Console.WriteLine(10);
Console.WriteLine(20);

Output:

10
20

9. Input and Output in Python

Python has a very simple input syntax.

Read an Integer

n = int(input())

Input:

10

Read a String

name = input()

Read Two Integers

a, b = map(int, input().split())

print(a + b)

Input:

10 20

Output:

30

Read an Array

arr = list(map(int, input().split()))

Input:

10 20 30 40 50

Result:

[10, 20, 30, 40, 50]

10. Input and Output in Java

Read an integer:

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

Read two integers:

int a = sc.nextInt();
int b = sc.nextInt();

System.out.println(a + b);

Input:

10 20

Output:

30

For large competitive-programming inputs, Java programmers often use BufferedReader with a custom fast scanner because it can be more efficient.


11. Input and Output in C++

Read an integer:

int n;
cin >> n;

Read two integers:

int a, b;
cin >> a >> b;

cout << a + b << endl;

Input:

10 20

Output:

30

Read an array:

int n;
cin >> n;

vector<int> arr(n);

for (int i = 0; i < n; i++)
{
    cin >> arr[i];
}

12. Understanding the Problem's Input Format

One of the most important DSA skills is learning to read the input format carefully.

Consider:

5
10 20 30 40 50

The problem might say:

The first line contains an integer N, representing the size of the array. The second line contains N integers.

You should translate that into:

N = 5

Array:
10
20
30
40
50

Then your program can process the array.


13. Multiple Test Cases

Many DSA problems contain multiple test cases.

Example:

3
10 20
5 7
100 200

The first number:

3

means there are three test cases.

Each test case contains two numbers.

C#

int t = int.Parse(Console.ReadLine());

while (t-- > 0)
{
    string[] input = Console.ReadLine().Split();

    int a = int.Parse(input[0]);
    int b = int.Parse(input[1]);

    Console.WriteLine(a + b);
}

Output:

30
12
300

14. Example: Find the Maximum Number

Problem

Given N integers, find the largest number.

Input

5
10 45 20 80 30

Output

80

C# Solution

int n = int.Parse(Console.ReadLine());

int[] arr = Console.ReadLine()
    .Split()
    .Select(int.Parse)
    .ToArray();

int max = arr[0];

for (int i = 1; i < n; i++)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}

Console.WriteLine(max);

Complexity

The array is traversed once.

Time Complexity:

O(N)

Space Complexity:

O(N)

when the array itself is stored.


15. Example: Sum of Array Elements

Input

5
10 20 30 40 50

Output

150

C#

int n = int.Parse(Console.ReadLine());

int[] arr = Console.ReadLine()
    .Split()
    .Select(int.Parse)
    .ToArray();

int sum = 0;

for (int i = 0; i < n; i++)
{
    sum += arr[i];
}

Console.WriteLine(sum);

The algorithm visits every element once.

Time Complexity:

O(N)

16. Handling Large Input

In competitive programming, the input can contain thousands or millions of values.

For example:

100000
1 2 3 4 5 ...

Reading input inefficiently can become a performance problem.

In such situations, languages provide faster input techniques.

For C#, a common approach is to read the complete input:

string input = Console.In.ReadToEnd();

Then tokenize it and process the values.

For most beginner DSA problems, however, Console.ReadLine() is sufficient.

Learn fast input when you start solving problems with large constraints.


17. Common Input Mistakes

Mistake 1: Treating numbers as strings

Incorrect:

string a = Console.ReadLine();
string b = Console.ReadLine();

Console.WriteLine(a + b);

For:

10
20

The result may be:

1020

instead of:

30

Convert the input:

int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());

Mistake 2: Wrong array size

If the problem says:

5
10 20 30 40 50

the array contains five values.

Always understand what N represents before creating the array.


Mistake 3: Incorrect loop boundary

Incorrect:

for (int i = 0; i <= arr.Length; i++)

This can access an invalid index.

Correct:

for (int i = 0; i < arr.Length; i++)

Mistake 4: Printing extra text

If the expected output is:

30

Do not print:

The answer is 30

unless the problem explicitly asks for that format.

Online judges generally compare your output with the expected output.


18. Input → Processing → Output

A useful way to think about every DSA problem is:

┌─────────────┐
│    Input    │
└──────┬──────┘
       ↓
┌─────────────┐
│    Store    │
│    Data     │
└──────┬──────┘
       ↓
┌─────────────┐
│   Process   │
│    Data     │
└──────┬──────┘
       ↓
┌─────────────┐
│   Output    │
└─────────────┘

For example:

Input:
5
10 20 30 40 50

       ↓

Store:
[10, 20, 30, 40, 50]

       ↓

Process:
Calculate sum

       ↓

Output:
150

This pattern is the foundation for almost every algorithm.


19. Practice Problems

Try solving these problems without looking at the solution.

Beginner

1. Read and Print

Read an integer and print it.

Input:

25

Output:

25

2. Add Two Numbers

Input:

10 20

Output:

30

3. Calculate Average

Input:

10 20 30

Output:

20

4. Sum of N Numbers

Input:

5
1 2 3 4 5

Output:

15

5. Find Maximum

Input:

5
10 50 20 80 30

Output:

80

6. Find Minimum

Input:

5
10 50 20 80 30

Output:

10

7. Count Even Numbers

Input:

6
1 2 3 4 5 6

Output:

3

20. What You Should Learn Next

Once you understand input and output, follow this DSA learning path:

Input & Output
      ↓
Time & Space Complexity
      ↓
Arrays
      ↓
Strings
      ↓
Searching
      ↓
Sorting
      ↓
Hashing
      ↓
Two Pointers
      ↓
Sliding Window
      ↓
Linked List
      ↓
Stack
      ↓
Queue
      ↓
Recursion
      ↓
Binary Search
      ↓
Trees
      ↓
Heap / Priority Queue
      ↓
Graphs
      ↓
Greedy
      ↓
Backtracking
      ↓
Dynamic Programming

Key Takeaways

  • Understand the input format before writing your algorithm.
  • Convert input into the correct data type.
  • Arrays usually require careful index handling.
  • Understand the difference between Write and WriteLine.
  • Multiple test cases are common in coding problems.
  • Do not print unnecessary text in online judges.
  • Always check the constraints before choosing your algorithm.
  • Think of every problem as Input → Processing → Output.

With these fundamentals in place, you are ready to start learning the core DSA topics.

Related

Found a problem on this page, or something that could be clearer?

Goes straight to the author. Not published anywhere.