0% found this document useful (0 votes)
4 views39 pages

Arrays Codes

This document provides a comprehensive overview of arrays in programming, specifically focusing on Java and C#. It covers various topics including ArrayLists, operations on arrays (search, insert, delete), finding the largest and second largest elements, checking if an array is sorted, reversing an array, removing duplicates, moving zeros to the end, and left rotating an array. Each topic includes explanations, examples, and links to code implementations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

Arrays Codes

This document provides a comprehensive overview of arrays in programming, specifically focusing on Java and C#. It covers various topics including ArrayLists, operations on arrays (search, insert, delete), finding the largest and second largest elements, checking if an array is sorted, reversing an array, removing duplicates, moving zeros to the end, and left rotating an array. Each topic includes explanations, examples, and links to code implementations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Arrays Codes GFG DSA

Brace yourself as we delve into the captivating world of Arrays. Prepare to unlock the power of organized
data, where each element holds a unique story waiting to be explored.

In this video, you will learn: ArrayList in Java !!!

What is an ArrayList??
Java ArrayList is a part of the Java collection framework and it is a class of java.util package.
It provides us with dynamic arrays in Java. It has various advantages over normal fixed-size
arrays.

This video will enlighten you with the following concepts:

What is ArrayList
Advantages of ArrayList over normal Arrays
Constructors in ArrayList for creating an ArrayList

Codes:

ArrayList Syntax: https://ide.geeksforgeeks.org/4JP4AdiUSz


Using ArrayList as Arrays(Internal Working): https://ide.geeksforgeeks.org/BOz9kratJZ
ArrayList with EnsureCapacity Method: https://ide.geeksforgeeks.org/C2FrC2BYHD

Codes C#:

ArrayList Syntax: https://ide.geeksforgeeks.org/9aabeed5-b552-4847-b6f0-4914673713ed


Using ArrayList as Arrays(Internal Working): https://ide.geeksforgeeks.org/b41fbd5c-b9f9-4f78-
b2e6-df199aa58d11
ArrayList with EnsureCapacity Method: https://ide.geeksforgeeks.org/34d7d893-37c9-4374-9b89-
d6d82fe835c4

Operations on Arrays (Part 1)

DescriptionComments

Brace yourself as we delve into the captivating world of Arrays. Prepare to unlock the power
of organized data, where each element holds a unique story waiting to be explored.
In this video, you will learn: Operations of Arrays (Search Operation and Insert Operation) !!!

This video will enlighten you with the following concepts:

Get the i-th element


Implementation and Time Complexity
Update i-th element
Implementation and Time Complexity
Searching an Array
Searching in Unsorted Array
Linear Search
Implementation and Time Complexity
Searching in Sorted Array
Binary Search
Inserting in an Array
Inserting in a Fixed Size Array
Implementation and Time Complexity
Inserting at the end of Dynamic Sized Array
Implementation and Time Complexity

Codes:

Insert
C: https://ide.geeksforgeeks.org/jQp3TGd2FD
CPP: https://ide.geeksforgeeks.org/8WAeXcymsH
Java: https://ide.geeksforgeeks.org/7qP8h4Uvfm
C#: https://ide.geeksforgeeks.org/721f9d07-9cb7-4c17-adfe-ecb252ae65c1
Search(Unsorted Array)
C: https://ide.geeksforgeeks.org/250nusxi3G
CPP: https://ide.geeksforgeeks.org/G44GBZ1H7k
Java: https://ide.geeksforgeeks.org/G5RUNYH2kY
C#: https://ide.geeksforgeeks.org/fe37cb74-d197-4d2d-8dd7-920cb1abb99a

Operations on Arrays (Part 2)

DescriptionComments

Brace yourself as we delve into the captivating world of Arrays. Prepare to unlock the power
of organized data, where each element holds a unique story waiting to be explored.

In this video, you will learn: Operations of Arrays (Delete Operation) !!!

This video will enlighten you with the following concepts:


Deletion from an Array
Implementation of the deletion operation
Time Complexity for Deletion

Codes:

Deletion
C: https://ide.geeksforgeeks.org/MGz943EITw
CPP: https://ide.geeksforgeeks.org/uzR0nDeFt9
Java: https://ide.geeksforgeeks.org/r4jtWDSX3b
C#: https://ide.geeksforgeeks.org/a713337c-1c79-4130-a657-a209bf1284a3

Largest Element in an Array

894

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Find the
Largest Number in an Array !!!

Our Task: Given an array arr[ ] of size n, the task is to find the largest element in the given
array.

Example:

Input: arr[] = {10, 20, 4}

Output: 20

Input: arr[] = {20, 10, 20, 4, 100}

Output: 100

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach
1) Naive Method:

In this approach, we traverse the array for each element present in the array. We compare all
elements with each other to find the largest element in the array.
Time Complexity: O(n2)

2) Efficient Method:

One of the most simplest and basic approach to solve this problem is to simply traverse the
whole list and find the maximum among them.

Follow the steps below to implement this idea:

Create a local variable max to store the maximum among the list
Initialize max with the first element initially, to start the comparison.
Then traverse the given array from second element till end, and for each element:
Compare the current element with max
If the current element is greater than max, then replace the value of max with the
current element.
At the end, return and print the value of the largest element of array stored in max.

Time Complexity: O(n)

Codes:

cpp code-: https://ide.geeksforgeeks.org/ffebaccb-e6d7-454c-a8a6-4756b90cac4c

Java code-: https://ide.geeksforgeeks.org/f877a1a4-6993-430c-8cee-f891cebe2434

C# Code: https://ide.geeksforgeeks.org/0b694eea-f8fa-4884-a125-8f64b0b82a16

Second Largest Element in Array

1049

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Find the
Second Largest Number in an Array !!!

Our Task: Given an array arr[ ] of size n, the task is to find the Second largest element in the
given array.

Example:
Input: arr[] = {12, 35, 1, 10, 34, 1}

Output: The second largest element is 34.

Explanation: The largest element of the

array is 35 and the second

largest element is 34

Input: arr[] = {10, 5, 10}

Output: The second largest element is 5.

Explanation: The largest element of

the array is 10 and the second

largest element is 5

Input: arr[] = {10, 10, 10}

Output: The second largest does not exist.

Explanation: Largest element of the array

is 10 there is no second-largest element

We have 2 approaches to solve the problem:

Naive approach: Finding 2nd Largest element in two traversals


Efficient approach: Finding 2nd Largest element in one traversal

1) Naive Approach:

In this approach, we find the 2nd largest element in the array, by ignoring the largest element.
It requires two traversals of the array

Time Complexity: O( nlogn )

2) Efficient Approach:
In this approach, we find the 2nd largest element in the array, by a single traversal through
the array. We maintain the record of the Largest and Second Largest element, which
traversing through the array.

Time Complexity: O(n)

Codes:

Naive approach:

C: https://ide.geeksforgeeks.org/GSL56poBwL
C#: https://ide.geeksforgeeks.org/46350654-70c7-433b-a9e4-1a478646c26c
C++: https://ide.geeksforgeeks.org/online-cpp-compiler/2f19c35d-315d-43ab-be57-
c66cec235e58
Java: https://ide.geeksforgeeks.org/online-java-compiler/70b83565-00ce-4a71-bdb5-
df21026a1c99

Efficient approach:

C: https://ide.geeksforgeeks.org/2fsu6XqWn2
C#: https://ide.geeksforgeeks.org/357d06cc-6f99-4492-ace3-bddb34ede84f
C++14: https://ide.geeksforgeeks.org/online-cpp14-compiler/f3b5f728-c3ba-41f9-aa4c-
33ac62bab411
Java: https://ide.geeksforgeeks.org/online-java-compiler/2c9e7e5c-db16-484e-a853-
eaf27f1043e1

Check if an Array is Sorted

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Check if
the Array is Sorted !!!

Our Task: We are given an array containing n elements. Our task is to check whether the array
is sorted in ascending (non-decreasing/increasing) order or not.
Examples:

Input: arr[] = {8, 12, 15}

Output: Yes // Since all elements are in ascending order

Input: arr[] = {8, 10, 10, 12}

Output: Yes // Since all elements are in ascending order (elements may be repeated)

Input: arr[] = {10, 10}

Output: Yes // Equal values are considered sorted

Input: arr[] = {100}

Output: Yes // Single element is considered as sorted

Input: arr[] = {100, 20 ,200}

Output: No // Elements are not in ascending order

Input: arr[] = {200, 100}


Output: No // Since we are checking an array to be sorted in ascending order

We have 2 approaches to solve the problem: Naive Approach & Efficient Approach

1) Naive Approach

Time Complexity: O(n2)

Auxiliary Space: O(1)

2) Efficient Approach

Time Complexity: O(n)

Auxiliary Space: O(1)

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/WexgfRhvUP
Java: https://ide.geeksforgeeks.org/pQDTIm17BW
C#: https://ide.geeksforgeeks.org/0c7bff0c-bce2-4244-a5e9-66a45bbbfc3c
Naive Method
CPP: https://ide.geeksforgeeks.org/38F8vszDpa
Java: https://ide.geeksforgeeks.org/ovxubbMppg
C#: https://ide.geeksforgeeks.org/d076619d-2b21-4fb1-994b-2d3a6626ff94

Reverse an Array

641

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Reverse an
Array !!!

Our Task: Given an array (or string), the task is to reverse the array.
Examples :

Input : arr[] = {1, 2, 3}

Output : arr[] = {3, 2, 1}


Input : arr[] = {4, 5, 1, 2}

Output : arr[] = {2, 1, 5, 4}

Time Complexity : Theta(n)

Codes:

C: https://ide.geeksforgeeks.org/TP4E1UXCoZ
CPP: https://ide.geeksforgeeks.org/Q18XrGjaH0
Java: https://ide.geeksforgeeks.org/qkfXgy68Yc
c#: https://ide.geeksforgeeks.org/7c41ae9d-df2c-4242-9d33-d3e7272969c2

Remove duplicates from a sorted array

913

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Remove
Duplicates from a Sorted Array !!!

Our Task: Given a sorted array, the task is to remove the duplicate elements from the array.

Examples:

Input : arr[] = {2, 2, 2, 2, 2}

Output : arr[] = {2}

new size = 1

Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}

Output : arr[] = {1, 2, 3, 4, 5}


new size = 5

We have 2 approaches to solve the problem: Naive approach and Efficient approach

1) Naive Approach

In this approach, we traverse the array and find the distinct elements, which are then copied
to a new array. After all the distinct elements are copied to the new array, the elements from
the new array are transferred back to the original array.

Time Complexity : O(n)


Auxiliary Space : O(n) // new array for storing distinct elements is required

2) Efficient Approach:

In this approach we compare the current element with the previous distinct element and
check if the current element is a distinct element or not.

Time Complexity : O(n)


Auxiliary Space : O(1)

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/A1Q1TOct6d
Java: https://ide.geeksforgeeks.org/izwCGdV1Jq
Javascript: https://ide.geeksforgeeks.org/tryit.php/242f8428-b542-4a1b-b8a1-
c2938dc7ed22
C#: https://ide.geeksforgeeks.org/daf9f074-761f-43d8-b344-4f4afeb20577
Naive Method
CPP: https://ide.geeksforgeeks.org/aEelSCQWbn
Java: https://ide.geeksforgeeks.org/KZtvikbUxh
Javascript: https://ide.geeksforgeeks.org/tryit.php/dc5c5a74-cb9f-47eb-a7a2-
b546a92ccf0f
C#: https://ide.geeksforgeeks.org/8dfe8ddb-30fc-4dcf-b17f-5d2a20879346

Move Zeros to End

Report

DescriptionComments
In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Move
Zeros to End !!!

Our Task: Given a sorted array, the task is to remove the duplicate elements from the array.

Examples:

Input: arr[] = {1, 2, 0, 0, 0, 3, 6}

Output: 1 2 3 6 0 0 0

Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}

Output: 1 9 8 4 2 7 6 9 0 0 0 0 0

We have 2 approaches to solve the problem: Naive Solution and Efficient Solution

1) Naive Approach:

In this approach, we traverse the array and, as soon as we find a 0 element, we traverse to the
right of the 0, and swap it with the 1st non-0 element found.

Time Complexity: O(n2).


Auxiliary Space: O(1).

2) Efficient Approach

In this approach, we maintain a count of the non-0 elements traversed. When a 0 element is
found, we place the value of the non-0 element at the element place of arr[count].

Time Complexity: O(n).


Auxiliary Space: O(1).

Codes:

C:- https://ide.geeksforgeeks.org/7975c5e5-7f23-4e75-836b-743719385fe2
CPP:- https://ide.geeksforgeeks.org/065bc525-b5cb-495e-8189-305367818588
JAVA:- https://ide.geeksforgeeks.org/1be10b6f-8151-4210-a940-10e91c00f1de
JAVASCRIPT: https://ide.geeksforgeeks.org/tryit.php/7a215ead-abeb-4c25-88ea-
b4790769a8d6
C#: https://ide.geeksforgeeks.org/9170b16a-a21a-4cf6-84b3-df6139db10db

Left Rotate an Array by One

582

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Left
Rotate an Array by One !!!

Our Task: Given an array, the task is to Left Rotate an Array by One.

What is meant by the Left Rotation of an Array by One?

Left Rotation means a rotation that happens Counter-Clockwise (anticlockwise). The


elements are moved counterclockwise by one, which results in the elements moving back by
one position from their initial position.

Example:

Input: arr[] = {1,2,3,4,5}

Output: arr[] = {2,3,4,5,1}

Input: arr[] = {30,5,20}

Output: arr[] = {5,20,30}

Steps to Solve the Problem:

Store the 1st element(index 0) in a temporary variable.


Start from the 2nd element (index 1) and move the elements back by one position.
Update the value of the last element in the array, by the value of the 1st variable, which
was initially stored in the temporary variable.
Time Complexity: O(n)

Space Complexity: O(1)

Codes:

C: https://ide.geeksforgeeks.org/cNKe1oIksJ
CPP: https://ide.geeksforgeeks.org/e4yl4vr66h
Java: https://ide.geeksforgeeks.org/UMRjB1yGTP
Javascript: https://ide.geeksforgeeks.org/tryit.php/333d9b19-1d04-4449-b123-
3911bb584c9c
C#: https://ide.geeksforgeeks.org/47635e95-4ab5-4f62-ba1c-bfb42e5b45d0

Left Rotate an Array by D places

891

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Left
Rotate an Array by D Places !!!

Our Task: Given an array, the task is to Left Rotate an Array by D places.

What is meant by the Left Rotation of an Array by D places?

Left Rotation means a rotation that happens Counter-Clockwise (anticlockwise). The


elements are moved counterclockwise by D number of places, which results in the elements
moving back by D positions from their initial position.

Examples:

Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2

Output: 3 4 5 6 7 1 2

Input: arr[] = {3, 4, 5, 6, 7, 1, 2}, d=2


Output: 5 6 7 1 2 3 4

We have 3 approaches to solve the problem: Naive Approach, Better Approach, and Reversal
Approach(Efficient Approach)

1) Naive Approach:

In this approach, we rotate the array by one position for D times.

Time Complexity: O(nd)

Space Complexity: O(1)

2) Better Approach:

In this approach, we store the first D elements of the array in a new array, and shift the
remaining elements by D positions to the left. Finally we copy back the D elements from the
new array to the end of the original array.

Time Complexity: Theta(n)

Space Complexity: Theta(d)

3) Reversal Approach (Efficient):

This approach consists of 3 reversal steps:

Reverse the elements from 0 to d-1 index


Reverse the elements from d to n-1 index
finally reverse the whole array

Time Complexity: Theta(n)

Space Complexity: Theta(1)

Codes:

Reversal Method
C: https://ide.geeksforgeeks.org/xg5ff2Tvww
CPP: https://ide.geeksforgeeks.org/S3ZxpVUzFr
Java: https://ide.geeksforgeeks.org/adWW3ZzXjn
Javascript: https://ide.geeksforgeeks.org/tryit.php/50df2adb-c9dc-46d7-b9c1-
a06ae32e73af
C#: https://ide.geeksforgeeks.org/f0746c74-257d-44a0-b1d3-1d1bf0f4265a
Efficient Code
C: https://ide.geeksforgeeks.org/0M2T5V4GVy
CPP: https://ide.geeksforgeeks.org/bLMbGJtChv
Java: https://ide.geeksforgeeks.org/ZQiGeV2Vfk
Javascript: https://ide.geeksforgeeks.org/tryit.php/0bcdef2a-143f-4382-af8b-
c30963a76be0
C#: https://ide.geeksforgeeks.org/35337d6f-176c-4483-8c75-1fb4c0fb8b18
Naive Method
C: https://ide.geeksforgeeks.org/xVbBYEn41o
CPP: https://ide.geeksforgeeks.org/KVinCgnCa7
Java: https://ide.geeksforgeeks.org/wbT7F7RytD
Javascript: https://ide.geeksforgeeks.org/tryit.php/8aea2354-dbac-400b-bf2d-
9e88a5c9cc6d
C#: https://ide.geeksforgeeks.org/ad13b4f8-48ed-474b-b8fd-1b58cb77697a

Leaders in an Array problem

717

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Find the
Leaders in an Array !!!

Our Task: Given an array, the task is to write a program to print all the LEADERS in the array.

What is a Leader?

An element is a leader if it is greater than all the elements to its right side. And the rightmost
element is always a leader.

For example:

Input: arr[] = {16, 17, 4, 3, 5, 2},

Output: 17, 5, 2

Input: arr[] = {1, 2, 3, 4, 5, 2},

Output: 5, 2

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach
1) Naive Approach:

We use two loops in this approach. The outer loop runs from 0 to size – 1 and one by one
picks all elements from left to right. The inner loop compares the picked element to all the
elements on its right side. If the picked element is greater than all the elements to its right
side, then the picked element is the leader.

Time Complexity: O(n2)


Auxiliary Space: O(1)

2) Efficient Approach:

The idea is to scan all the elements from right to left in an array and keep track of the
maximum till now. When the maximum changes its value, print it.

Time Complexity: O(n)


Auxiliary Space: O(1)

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/cY8KYEJmka
Java: https://ide.geeksforgeeks.org/kZNeol7GKJ
C#: https://ide.geeksforgeeks.org/71da38df-f534-4383-a4f3-9f8a0a85ff9d
Naive Method
CPP: https://ide.geeksforgeeks.org/wkM5LEqJfW
Java: https://ide.geeksforgeeks.org/Pj0jk4V0Vd
C#: https://ide.geeksforgeeks.org/e452061f-6e52-41f0-ba58-8b44b364613b

Maximum Difference Problem with Order

721

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Maximum
Difference Problem with Order !!!

Our Task: Given an array arr[] of integers, find out the maximum difference between any two
elements such that the larger element appears after the smaller number.

Examples :
Input : arr = {2, 3, 10, 6, 4, 8, 1}

Output : 8

Explanation : The maximum difference is between 10 and 2.

Input : arr = {7, 9, 5, 6, 3, 2}

Output : 2

Explanation : The maximum difference is between 9 and 7.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:

We use two loops. In the outer loop, pick elements one by one and in the inner loop calculate
the difference of the picked element with every other element in the array and compare the
difference with the maximum difference calculated so far. Below is the implementation of the
above approach :

Time Complexity : O(n^2)


Auxiliary Space : O(1)

2) Efficient Approach:

In this method, instead of taking difference of the picked element with every other element,
we take the difference with the minimum element found so far. So we need to keep track of 2
things:

Maximum difference found so far (max_diff).


Minimum element visited so far (min_element).

Time Complexity : O(n)


Auxiliary Space : O(1)

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/eKkmrh9wSh
Java: https://ide.geeksforgeeks.org/pEGlK0DRaR
Javascript: https://ide.geeksforgeeks.org/tryit.php/9b1fc6a4-27b2-42b1-b138-
c040af905327
C#:https://ide.geeksforgeeks.org/2ae53b67-f351-4126-a1de-b85c657ddc90
C: https://ide.geeksforgeeks.org/online-c-compiler/1a48f952
Naive Method
CPP: https://ide.geeksforgeeks.org/bwEXxyI6VQ
Java: https://ide.geeksforgeeks.org/eHUBgtf6EI
Javascript: https://ide.geeksforgeeks.org/tryit.php/fdbd1ae5-6db3-4bf7-a61b-
139570e89e33
C#: https://ide.geeksforgeeks.org/3860eda4-9d91-4e7d-8842-b998ab2e59d8
C: https://ide.geeksforgeeks.org/online-c-compiler/d2d3820

Frequencies in a Sorted Array

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Find the
Frequencies in a Sorted Array !!!

Our Task: Given a sorted array, arr[] consisting of N integers, the task is to find the
frequencies of each array element.

Examples:

Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10}

Output: Frequency of 1 is: 3

Frequency of 2 is: 1

Frequency of 3 is: 2

Frequency of 5 is: 2

Frequency of 8 is: 3

Frequency of 9 is: 2

Frequency of 10 is: 1

Input: arr[] = {2, 2, 6, 6, 7, 7, 7, 11}

Output: Frequency of 2 is: 2

Frequency of 6 is: 2
Frequency of 7 is: 3

Frequency of 11 is: 1

To solve this problem, we use the following approach:

The idea is to maintain a variable to keep track of the frequency of elements while traversing
the array. Follow the steps below to solve the problem:

Initialize a variable, say freq as 1 to store the frequency of elements.


Iterate in the range [1, N-1] using the variable i and perform the following steps:
If the value of arr[i] is equal to arr[i-1], increment freq by 1.
Else print value the frequency of arr[i-1] obtained in freq and then update freq to 1.
Finally, after the above step, print the frequency of the last distinct element of the array
as freq.

Time Complexity: O(N)


Auxiliary Space: O(1)

Codes:

CPP: https://ide.geeksforgeeks.org/996fe899-43fb-431b-b5e2-780661bedb1a
Java: https://ide.geeksforgeeks.org/585972b4-8611-428f-aae9-f8df1a78bd92
C#: https://ide.geeksforgeeks.org/34d5f355-dd71-42ec-ba2d-4788d538cc9f
Javascript: https://ide.geeksforgeeks.org/tryit.php/4ac2e625-efb9-420a-acf3-
9f340554fdff

Stock Buy and Sell Problem (Part 1)

535

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Stock Buy
and Sell Problem !!!

Our Task: The cost of a stock on each day is given in an array. Find the maximum profit that
you can make by buying and selling on those days. If the given array of prices is sorted in
decreasing order, then profit cannot be earned at all.

Examples:
Input: arr[] = {100, 180, 260, 310, 40, 535, 695}

Output: 865

Explanation: Buy the stock on day 0 and sell it on day 3 => 310 – 100 = 210

Buy the stock on day 4 and sell it on day 6 => 695 – 40 = 655

Maximum Profit = 210 + 655 = 865

Input: arr[] = {4, 2, 2, 2, 4}

Output: 2

Explanation: Buy the stock on day 1 and sell it on day 4 => 4 – 2 = 2

Maximum Profit = 2

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

In this video, we will discuss the Naive approach.

In the next part of the video, the Efficient Approach will be discussed.

1) Naive Approach

A simple approach is to try buying the stocks and selling them every single day when
profitable and keep updating the maximum profit so far.

Follow the steps below to solve the problem:

Try to buy every stock from start to end – 1


After that again call the maxProfit function to calculate answer
curr_profit = price[j] – price[i] + maxProfit(start, i – 1) + maxProfit(j + 1, end)
profit = max(profit, curr_profit)

Time Complexity: O(n2), Trying to buy every stock and exploring all possibilities.
Auxiliary Space: O(1)

Codes:

CPP: https://ide.geeksforgeeks.org/F0zCflXr4A
Java: https://ide.geeksforgeeks.org/EPIIxZg2gG
Javascript: https://ide.geeksforgeeks.org/tryit.php/68ceeba4-5f05-4f8a-aa38-
f69911b7a941
C#: https://ide.geeksforgeeks.org/ea2b3d5d-1328-49c0-bda3-5f65d3953aff
Stock Buy and Sell problem (Part 2)

551

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Stock Buy
and Sell Problem !!!

Our Task: The cost of a stock on each day is given in an array. Find the maximum profit that
you can make by buying and selling on those days. If the given array of prices is sorted in
decreasing order, then profit cannot be earned at all.

Examples:

Input: arr[] = {100, 180, 260, 310, 40, 535, 695}

Output: 865

Explanation: Buy the stock on day 0 and sell it on day 3 => 310 – 100 = 210

Buy the stock on day 4 and sell it on day 6 => 695 – 40 = 655

Maximum Profit = 210 + 655 = 865

Input: arr[] = {4, 2, 2, 2, 4}

Output: 2

Explanation: Buy the stock on day 1 and sell it on day 4 => 4 – 2 = 2

Maximum Profit = 2

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

In this video, we will discuss the Efficient Solution of the problem

The Naive solution to the problem has been discussed in the previous video

Efficient Approach (Valley Peak Approach):

In this approach, we just need to find the next greater element and subtract it from the
current element so that the difference keeps increasing until we reach a minimum. If the
sequence is a decreasing sequence, so the maximum profit possible is 0.

Follow the steps below to solve the problem:

maxProfit = 0
if price[i] > price[i – 1]
maxProfit = maxProfit + price[i] – price[i – 1]

Time Complexity: O(n), Traversing over the array of size n


Auxiliary Space: O(1)

Codes:

CPP: https://ide.geeksforgeeks.org/XDa3wfa9Sf
Java: https://ide.geeksforgeeks.org/2DwByHrLiX
Javascript: https://ide.geeksforgeeks.org/tryit.php/7badfe7f-c288-4b67-aa7e-
7e5ce6e50cdf
C#: https://ide.geeksforgeeks.org/07165de6-e7a1-469e-8400-c4666b3543e4

Trapping Rain Water


820

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Trapping
Rain Water !!!

Our Task: Given an array of N non-negative integers arr[ ] representing an elevation map
where the width of each bar is 1, compute how much water it is able to trap after rain.

Note: The array elements represent the height of the bars.

Examples:

Input: arr[] = {3, 0, 2, 0, 4}


Output: 7
Explanation: Structure is like below.
We can trap “3 units” of water between 3 and 2,
“1 unit” on top of bar 2 and “3 units” between 2 and 4.
We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1)Naive Approach

Complexity Analysis:

Time Complexity: O(n2). There are two nested loops traversing the array.
Space Complexity: O(1). No extra space is required.

2) Efficient Approach

Complexity Analysis:

Time Complexity: O(N). Only one traversal of the array is needed, So time Complexity is
O(N).
Space Complexity: O(N). Two extra arrays are needed, each of size N.

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/uf1ZkWjsqn
Java: https://ide.geeksforgeeks.org/rKR6wcZcdF
Javascript: https://ide.geeksforgeeks.org/tryit.php/7badfe7f-c288-4b67-aa7e-
7e5ce6e50cdf
C#: https://ide.geeksforgeeks.org/tryit.php/107d1522-8ff6-47e9-aba2-5e8202d5fdd5
Naive Method
CPP: https://ide.geeksforgeeks.org/owf5GaW3jq
Java: https://ide.geeksforgeeks.org/Csr6VM2nU4
Javascript: https://ide.geeksforgeeks.org/tryit.php/5d4525a8-b67a-4a75-b64d-
cd53b14ec68e
C#: https://ide.geeksforgeeks.org/tryit.php/5d4525a8-b67a-4a75-b64d-cd53b14ec68e

Maximum consecutive 1s

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, To Find
Maximum Consecutive 1s !!!
Our Task: Given a binary array, find the count of the maximum number of consecutive 1's
present in the array.

Examples :

Input: arr[] = {1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1}

Output: 4

Input: arr[] = {0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}

Output: 1

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:

In this approach, we use two looks and traverse the array from start to end. At each element,
we check if it is 1 or 0. If the element is 1, we increment the count variable and count the
number of 1s along with it if any. After each completion of the inner loop, we find the
maximum between the current count and the previous count.

Time Complexity : O(n2)


Auxiliary Space : O(1)

2) Efficient Approach:

An efficient solution is to traverse the array from left to right. If we see a 1, we increment the
count and compare it with the maximum so far. If we see a 0, we reset the count to 0.

Time Complexity : O(n)


Auxiliary Space : O(1)

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/DomO12di9m
Java: https://ide.geeksforgeeks.org/CB2KT9XypS
Javascript: https://ide.geeksforgeeks.org/tryit.php/15bc4594-c0a9-4608-b143-
dcc0c6fee524
C#: https://ide.geeksforgeeks.org/d191ea0b-0227-499d-a7b9-fc9ccfb2d073
Naive Method
CPP: https://ide.geeksforgeeks.org/CSkbeeIHOE
Java: https://ide.geeksforgeeks.org/QmflrSLDGP
Javascript: https://ide.geeksforgeeks.org/tryit.php/cc2923aa-4255-41cd-ad61-
65cf5af01fdd
C#: https://ide.geeksforgeeks.org/986540e7-9ca3-47c7-9d19-f94e2a3ff849

Maximum subarray sum

766

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Maximum
Subarray Sum !!!

Our Task: Given an array arr[], the task is to find the elements of a contiguous subarray of
numbers that has the largest sum.

Examples:

Input: arr = [-2, -3, 4, -1, -2, 1, 5, -3]

Output: [4, -1, -2, 1, 5]

Explanation:

In the above input, the maximum contiguous subarray sum is 7 and the elements of the
subarray are [4, -1, -2, 1, 5]

Input: arr = [-2, -5, 6, -2, -3, 1, 5, -6]

Output: [6, -2, -3, 1, 5]

Explanation:

In the above input, the maximum contiguous subarray sum is 7 and the elements

of the subarray are [6, -2, -3, 1, 5]

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1)Naive Approach

The naive approach is to generate all the possible subarrays and print that subarray that has
the maximum sum.
Time complexity: O(n2)
Auxiliary Space: O(1)

2) Efficient Approach:

The idea is to maintain a variable max_ending that stores the maximum sum contiguous
subarray ending at current index and a variable res stores the maximum sum of contiguous
subarray found so far. Everytime there is a positive-sum value in max_ending compare it with
res and update res if it is greater than res.

Time complexity: O(n)


Auxiliary Space: O(1)

Codes:

C++ code - https://ide.geeksforgeeks.org/online-cpp-compiler/d05aaf7f-1088-49c3-90d2-


5aea4e2a51a5

JAVA code - https://ide.geeksforgeeks.org/a7e6b54a-3582-421e-ba47-f7cc9ca28505

JAVASCRIPT: https://ide.geeksforgeeks.org/tryit.php/41403112-bb64-408b-8e5b-
4cb47d6c044e

c#: https://ide.geeksforgeeks.org/090e8134-5134-4b64-b720-56b3fa98267d

Longest Even Odd Subarray


501

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Longest Even
Odd Subarray !!!

Our Task: Given an array a[ ] of N integers, the task is to find the length of the longest
Alternating Even Odd subarray present in the array.

Examples:

Input: a[] = {1, 2, 3, 4, 5, 7, 9}


Output: 5
Explanation:
The subarray {1, 2, 3, 4, 5} has alternating even and odd elements.
Input: a[] = {1, 3, 5}
Output: 1
Explanation:
There are only odd numbers, so we can count any one of them.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1)Naive Approach

The idea is to consider every subarray and find the length of even and odd subarrays.

Time Complexity: O(n2), Iterating over every subarray therefore N2 are possible
Auxiliary Space: O(1)

2)Efficient Approach

By simply storing the nature of the previous element we encounter( odd or even) and
comparing it with the next element.

Time Complexity: O(n), Since we need to iterate over the whole array once
Auxiliary Space: O(1)

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/Uz3vWPUUNM
Java: https://ide.geeksforgeeks.org/Sp7XlX1yZ8
Javascript: https://ide.geeksforgeeks.org/tryit.php/cfca63ad-dc2d-4f7e-bd6b-
e6dfba24a775
C#: https://ide.geeksforgeeks.org/c93378f5-021d-488a-bcca-19db2da80a7e
Naive Method
CPP: https://ide.geeksforgeeks.org/BZOgWE7H8z
Java: https://ide.geeksforgeeks.org/RZs6tLQKxz
Javascript: https://ide.geeksforgeeks.org/tryit.php/a14b9939-b040-4953-a179-
882b526f16a0
C#: https://ide.geeksforgeeks.org/13345d90-75e8-4729-8629-46aa356512d8

Maximum Circular Sum Subarray

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Maximum
Circular Sum Subarray !!!
Our Task: Given a circular array of size n, find the maximum subarray sum of the non-empty
subarray.

What is a Circular Subarray?

An array is called circular if we consider the first element as the next of the last element.

Example: arr[ ] ={1, 2, 3}

The subarrays of this circular array can be: {1} {2} {3} {1, 2} {2, 3} {3, 1} {1, 2, 3} {2, 3, 1} {3, 1, 2}

Examples:

Input: arr[] = {8, -8, 9, -9, 10, -11, 12}


Output: 22
Explanation: Subarray 12, 8, -8, 9, -9, 10 gives the maximum sum, that is 22.

Input: arr[] = {10, -3, -4, 7, 6, 5, -4, -1}


Output: 23
Explanation: Subarray 7, 6, 5, -4, -1, 10 gives the maximum sum, that is 23.

Input: arr[] = {-1, 40, -14, 7, 6, 5, -4, -1}


Output: 52
Explanation: Subarray 7, 6, 5, -4, -1, -1, 40 gives the maximum sum, that is 52.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1)Naive Approach:

The approach is to use two loops and iterate thought-out the array in a circular manner. After
each iteration, take the maximum of the current maximum and previous maximum

Time Complexity: O(n2)


Auxiliary Space: O(1)

2) Efficient Approach:

The idea is to modify Kadane's algorithm to find a minimum contiguous subarray sum and the
maximum contiguous subarray sum, then check for the maximum value between the
max_value and the value left after subtracting min_value from the total sum.

The idea is to take the maximum of the following two:

Maximum Sum of a Normal Array (Using Kadane)


Maximum sum of a Circular Subarray
Time Complexity: O(n), where n is the number of elements in the input array. Linear traversal
of the array is needed.
Auxiliary Space: O(1), No extra space is required.

Codes:

Efficient Method
CPP: https://ide.geeksforgeeks.org/5OjvBfI5Ql
Java: https://ide.geeksforgeeks.org/h8wjdmXCTd
Javascript: https://ide.geeksforgeeks.org/tryit.php/905d2be1-5251-451b-80bc-
a0fe8642a182
C#: https://ide.geeksforgeeks.org/5ea9b685-b1a6-4744-8767-9c9800e75f6d
Naive Method
CPP: https://ide.geeksforgeeks.org/gLVLZRROoJ
Java: https://ide.geeksforgeeks.org/K5MU1mmyUs
Javascript: https://ide.geeksforgeeks.org/tryit.php/72fc7355-1545-43af-84ba-
ce776565c52e
C#: https://ide.geeksforgeeks.org/5ad97f2a-f3a1-4313-bbad-cdb67251bef0

Majority Element
632

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Majority
Element !!!

Our Task: Find the majority element in the array. A majority element in an array A[] of size n is
an element that appears more than n/2 times (and hence there is at most one such element).

What is a majority element?

A majority element in an array A[] of size n is an element that appears more than n/2 times
(and hence there is at most one such element).

Examples :

Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output : 4
Explanation: The frequency of 4 is 5 which is greater than the half of the size of the array
size.
Input : {3, 3, 4, 2, 4, 4, 2, 4}
Output : No Majority Element
Explanation: There is no element whose frequency is greater than the half of the size of the
array size.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1)Naive Approach:

The basic solution is to have two loops and keep track of the maximum count for all different
elements. If the maximum count becomes greater than n/2 then break the loops and return
the element having the maximum count. If the maximum count doesn’t become more than
n/2 then the majority element doesn’t exist.

Time Complexity: O(n2), A nested loop is needed where both the loops traverse the array
from start to end.
Auxiliary Space: O(1), No extra space is required.

2) Efficient Approach (Moore’s Voting Algorithm):

This is a two-step process:

The first step gives the element that may be the majority element in the array. If there is a
majority element in an array, then this step will definitely return majority element,
otherwise, it will return candidate for majority element.
Check if the element obtained from the above step is the majority element. This step is
necessary as there might be no majority element.

Time Complexity: O(n), As two traversal of the array, is needed, so the time complexity is
linear.
Auxiliary Space: O(1), As no extra space is required.

Codes:

Efficient Solution
CPP: https://ide.geeksforgeeks.org/AAU0PbQvy4
Java: https://ide.geeksforgeeks.org/GiGZlUePfF
JAVASCRIPT: https://ide.geeksforgeeks.org/tryit.php/c5f0ba1f-538a-443b-a183-
0cabb32368f6
C#: https://ide.geeksforgeeks.org/7aa9a27c-68ee-4da0-93cc-b354141279ab
Naive Solution
CPP: https://ide.geeksforgeeks.org/C6aveb7Lcc
Java: https://ide.geeksforgeeks.org/uD30hi4IFJ
Javascript:https://ide.geeksforgeeks.org/tryit.php/a5d528ce-0158-4546-9c26-
157d34f86024
C#: https://ide.geeksforgeeks.org/bc799745-f404-4634-b6eb-388c614bd300
Minimum Consecutive Flips

575

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Minimum
Consecutive Flips!!!

Our Task: Given a binary array, we need to convert this array into an array that either contains
all 1s or all 0s. We need to do it using the minimum number of group flips.

Examples :

Input : arr[] = {1, 1, 0, 0, 0, 1}


Output : From 2 to 4
Explanation : We have two choices, we make all 0s or do all 1s. We need to do two group flips
to make all elements 0 and one group flip to make all elements 1. Since making all elements
1 takes the least group flips, we do this.
Input : arr[] = {1, 0, 0, 0, 1, 0, 0, 1, 0, 1}
Output :
From 1 to 3
From 5 to 6
From 8 to 8
Input : arr[] = {0, 0, 0}
Output :
Explanation : Output is empty, we need not to make any change
Input : arr[] = {1, 1, 1}
Output :
Explanation : Output is empty, we need not to make any change
Input : arr[] = {0, 1}
Output :
From 0 to 0
OR
From 1 to 1
Explanation : Here number of flips are same either we make all elements as 1 or all elements
as 0.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:
A Naive Solution is to

Traverse the two traversals of the array.


We first traverse to find the number of groups of 0s and the number of groups of 1.
We find the minimum of these two.
Then we traverse the array and flip the 1s if groups of 1s are less. Otherwise, we flip 0s.

2) Efficient Approach:

The aim is to do it with one traversal of array

An Efficient Solution is based on the below facts :

There are only two types of groups (groups of 0s and groups of 1s)
Either the counts of both groups are same or the difference between counts is at most 1.
For example, in {1, 1, 0, 1, 0, 0} there are two groups of 0s and two groups of 1s. In
example, {1, 1, 0, 0, 0, 1, 0, 0, 1, 1}, count of groups of 1 is one more than the counts of 0s.

Based on the above facts, we can conclude that if we always flip the second group and other
groups that of the same type as the second group, we always get the correct answer.

Time Complexity: O(n)


Auxiliary Space: O(1)

Codes:

CPP: https://ide.geeksforgeeks.org/cPQnrtDbjm
Java: https://ide.geeksforgeeks.org/FKwu2LcxRe
Javascript: https://ide.geeksforgeeks.org/tryit.php/eaf83866-756b-4bc1-a454-
349710007178
C#: https://ide.geeksforgeeks.org/7ff10b32-7768-4dd1-b060-4e4381036a5a
Python: https://ide.geeksforgeeks.org/eb10a382

Sliding Window Technique

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Sliding
Window Technique!!!

Our Task: Given an array of integers of size 'n'. Our aim is to calculate the maximum sum of 'k'
consecutive elements in the array.
Examples :

Input : arr[] = {100, 200, 300, 400}

k=2

Output : 700

Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}

k=4

Output : 39

We get maximum sum by adding subarray {4, 2, 10, 23}

of size 4.

Input : arr[] = {2, 3}

k=3

Output : Invalid

There is no subarray of size 3 as size of whole

array is 2.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:

The Naive Approach to solve this problem is to calculate sum for each of the blocks of K
consecutive elements and compare which block has the maximum sum possible.

Time Complexity: O(n2)


Auxiliary Space: O(1)

2) Efficient Approach (Window Sliding Technique):

The above problem can be solved in Linear Time Complexity by using Window Sliding
Technique by avoiding the overhead of calculating sum repeatedly for each block of k
elements.
Time Complexity is O(n).

Codes:

Maximum Sum of K Consecutive elements(Efficient)


CPP: https://ide.geeksforgeeks.org/QSMe98qHhN
Java: https://ide.geeksforgeeks.org/BOupKnipIW
javascript: https://ide.geeksforgeeks.org/tryit.php/227e8afd-1024-43dd-ab16-
9a645b785dbe
C# https://ide.geeksforgeeks.org/693ac5fe-55c1-44d0-8d18-2fe3bc826593
Maximum Sum of K Consecutive elements(Naive)
CPP: https://ide.geeksforgeeks.org/O3g1sYcsh9
Java: https://ide.geeksforgeeks.org/5K3TuTmnwJ
Javascript: https://ide.geeksforgeeks.org/tryit.php/3a4f0601-5ff6-4afe-8dd3-
c4c793ec1547
C# : https://ide.geeksforgeeks.org/5130d00a-eab6-4f6c-9d0a-e74b77ca5ab5

Subarray with Given Sum

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Subarray
with given Sum !!!

Our Task: Given an array arr[ ] of non-negative integers and an integer sum, find a subarray
that adds to a given sum.

Examples:

Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33


Output: Sum found between indexes 2 and 4
Explanation: Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33

Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7


Output: Sum found between indexes 1 and 4
Explanation: Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7

Input: arr[] = {1, 4}, sum = 0


Output: No subarray found
Explanation: There is no subarray with 0 sum
We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:

The idea is to consider all subarrays one by one and check the sum of every subarray. The
following program implements the given idea.
Run two loops: the outer loop picks a starting point i and the inner loop tries all subarrays
starting from i.

Time Complexity: O(n2), Trying all subarrays from every index, used nested loop for the same
Auxiliary Space: O(1).

2) Efficient Approach (Using Sliding Window):

The idea is simple as we know that all the elements in subarray are positive so, If a subarray
has sum greater than the given sum then there is no possibility that adding elements to the
current subarray will be equal to the given sum. So the Idea is to use a similar approach to a
sliding window.

Time Complexity: O(n)


Auxiliary Space: O(1). Since no extra space has been taken.

Codes:

Find subarray with given sum


CPP: https://ide.geeksforgeeks.org/DarCwv91az
Java: https://ide.geeksforgeeks.org/gRDd6ZRxDe
Javascript: https://ide.geeksforgeeks.org/tryit.php/4be040ad-fe6a-4f38-b171-
5d4670965e10
C#: https://ide.geeksforgeeks.org/966ec60d-a9ac-4a21-b1ec-72a8bb861a6b
Find subarray with given sum Naive
CPP: https://ide.geeksforgeeks.org/83a833b3-00ac-48bb-aa8b-44f7cb34f26b
Java: https://ide.geeksforgeeks.org/f5e39dd5-db6f-45d5-89df-6b1cbab4f304
Javascript: https://ide.geeksforgeeks.org/tryit.php/367b0602-03d2-4616-afe5-
fb38db34da27
C#: https://ide.geeksforgeeks.org/4a5448ea-055e-463b-bf15-0932c0eec6e4

Prefix Sum
0

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Prefix Sum
Technique !!!
Our Task: Given an array arr[] of size n, its prefix sum array is another array prefixSum[ ] of the
same size, such that the value of prefixSum[i] is arr[0] + arr[1] + arr[2] … arr[i].

We need to create the prefix Array so that getsum() queries can be resolved in O(1) time.

Examples :

Input : arr[] = {10, 20, 10, 5, 15}


Output : prefixSum[] = {10, 30, 40, 45, 60}
Explanation : While traversing the array, update the element by adding it with its previous
element.
prefixSum[0] = 10,
prefixSum[1] = prefixSum[0] + arr[1] = 30,
prefixSum[2] = prefixSum[1] + arr[2] = 40 and so on.

To fill the prefix sum array, we run through index 1 to last and keep on adding the present
element with the previous value in the prefix sum array.

Time Complexity: O(n)


Auxiliary Space: O(n)

Codes:

Naive Solution

CPP : Naive CPP Solution


Java : Naive Java Solution
Javascript: https://ide.geeksforgeeks.org/tryit.php/f241c423-f6b8-48ee-9c8f-
c8c9ac34d27c
C# : https://ide.geeksforgeeks.org/17cf73a5-a93a-4294-8c01-15c52f8df2ad

Efficient Solution

CPP : Efficient Solution


Java : Efficient Solution
Javascript: https://ide.geeksforgeeks.org/tryit.php/35a147f0-f65c-465c-b01f-
cea4b9bd1ec1
C#: https://ide.geeksforgeeks.org/b3936f5a-b614-41de-967b-862cce47fef7

Equilibrium Point

Report
DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Finding the
Equilibrium Point !!!

Our Task: Given a sequence arr[ ] of size n, Write a function int equilibrium(int[] arr, int n) that
returns an equilibrium index (if any) or -1 if no equilibrium index exists.

What is an Equilibrium Point?

The equilibrium index of an array is an index such that the sum of elements at lower indexes
is equal to the sum of elements at higher indexes.

Examples:

Input: A[] = {-7, 1, 5, 2, -4, 3, 0}


Output: 3 //index of 2
3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]

Input: A[] = {1, 2, 3}


Output: -1

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:

To solve the problem follow the below idea: Use two loops. The Outer loop iterates through
all the element and inner loop finds out whether the current index picked by the outer loop is
equilibrium index or not.

Time Complexity: O(n2)


Auxiliary Space: O(1)

2) Efficient Approach

To solve the problem follow the below idea:

The idea is to get the total sum of the array first. Then Iterate through the array and keep
updating the left sum which is initialized as zero. In the loop, we can get the right sum by
subtracting the elements one by one.

Time Complexity: O(n)


Auxiliary Space: O(1)

Codes:
C++: https://ide.geeksforgeeks.org/online-cpp14-compiler/77d1d798-c381-4723-9c41-
8c81ae178937

Java: https://ide.geeksforgeeks.org/online-cpp14-compiler/cfc9b730-6b4d-434c-8d67-
813cc3feada9

Maximum Appearing Element


0

Report

DescriptionComments

In a realm where numbers hold secrets, a captivating challenge awaits, which is, Finding
Maximum Appearing Element !!!

Our Task: Given two arrays L[ ] and R[ ] of size N where L[i] and R[i] (0 ? L[i], R[i] < 106)
denotes a range of numbers, the task is to find the maximum occurred integer in all the
ranges. If more than one such integer exists, print the smallest one.

Thus 4 is the Most appeared Element in the Ranges

Examples:

Input: L[ ] = {1, 4, 3, 1}, R[ ] = {15, 8, 5, 4}


Output: 4

Explanation: Overall ranges are: {1,2,3,4,5,6,7,8,9,10,11,12,13,14 15}, {4,5,6,7,8}, {3,4,5},


{1,2,3,4}.

In all these ranges, 4 appears the most times.

Input: L[ ] = {1, 5, 9, 13, 21}, R[ ] = {15, 8, 12, 20, 24}


Output: 5
Explanation: Overall Ranges are: {1,2,3,4,5,6,7,8,9,10,11,12,13,14 15}, {5,6,7,8}, {9,10,11,12},
{13,14,15,16,17,18,19,20},{21,22,23,24}
In these ranges, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 all appear 2 times. The smallest number
among all are 5.

We have 2 approaches to solve the problem: Naive Approach and Efficient Approach

1) Naive Approach:

The idea is to:


Traverse through all the ranges. Then for every range, count frequencies, make a hash table
(array) to store every item. Then traverse through other ranges and increment the frequency
of every item. The item with the highest frequency is our answer.

Time Complexity: O(N*M). Here N is the number of ranges and M is the maximum number of
elements in any of the ranges.
Auxiliary Space: O(M). For Hash table.

2) Efficient Approach:

Below is the idea to solve the problem:

The idea is to use the Difference array technique. Create a vector initialized with value zero.
Iterate through every range and mark the presence of the beginning of every range by
incrementing the start of the range with one i.e. arr[L[i]]++ and mark the end of the range by
decrementing at index one greater than the end of range by one i.e. arr[R[i]+1]–.

Now when computing the prefix sum, Since the beginning is marked with one, all the values
after beginning will be incremented by one. Now as increment is only targeted only till the
end of the range, the decrement on index R[i]+1 prevents that for every range i.

Time Complexity: O(N + MAX)


Auxiliary space: O(MAX)

C++ Code :- https://ide.geeksforgeeks.org/4bf6c12d-c304-4491-acab-73ac926f2d27


Java Code :- https://ide.geeksforgeeks.org/1d037c1f-7ffe-4727-a54c-7f022184885a

Javascript: https://ide.geeksforgeeks.org/tryit.php/8942326b-b4d0-4411-b8be-750f53ca3a80

C#: https://ide.geeksforgeeks.org/75c8c2ad-4aae-450a-8054-d01b47bf7d56

You might also like