Hello everyone!!💖
Today is all about arrays🤩. We know array is the most commonly used data structure of all. I guess most of us have got stuck with array concepts while coding, right? Why late? let's learn it perfectly so that we can solve any problem using an array.
CONTENTS
- Basic Operations
- Rotating array using juggling algorithm
- Sliding Window Technique
- Prefix sum array
- Bonus concepts and problems
Basic Operations
So, before starting with concepts we should be clear with the common syntax like declaration, instantiation, initialization, passing an array to method, etc.
Note: I will be providing java code with a Github link for every concept I discuss here!😊
Insertion of an element
- At the end of an array
CODE :- code for inserting an element at the end//pseudocode int[] arr = {1, 2, 3, 4, 5} insert k=7 //after insertion arr = [1, 2, 3, 4, 5, 7]
- At a specified position
CODE:- Code for inserting element at specified position//pseudocode int[] arr = {1, 2, 3, 4, 5} insert k=7, pos=3 //after insertion arr= [1, 2, 3, 7, 4, 5]
- At the end of an array
Deletion
//pseudocode int[] arr = {1, 2, 3, 4, 5} del value=3 //after deletion arr=[1, 2, 4, 5]
Sorting
CODE:- code for sort
In this link, I have not used in-built methods or did not write a well-optimised code. Solved it in a way that you could understand😋(if newbie).
Searching an element
//pseudocode int[] arr = {1, 2, 3, 4, 5} search val=7 if found, print true else false
Reversing an array
//pseudocode int[] arr = {1, 2, 3, 4, 5} //after reversing arr=[5, 4, 3, 2, 1]
CODE:- Code for reversing an array
Rotating array using juggling algorithm
By name, we can understand that rotation means simply shifting elements of an array by a specified number of positions. Rotations can be of 2 types: left and right. See below examples to get a clear understanding of what it is.
Left Rotation: Here, k=2 (where k is the number of positions to be shifted left).
Right Rotation: Here, k=2 (where k is the number of positions to be shifted right).
Check this article to know more! Juggling Algorithm😊
Sliding Window Technique
Consider the following example, find Maximum sum of 'k' consecutive elements in an array.
arr[] = {5, 2, -1, 0, 3}
k = 3
Output : 6
To find this we generally use nested for-loop. So, this technique shows how a nested for loop in a few problems can be converted to a single for loop and hence reducing the time complexity.
The Approach:
CODE:- Sliding Window Technique Code
Prefix sum array
//pseudocode
Input : arr[] = {10, 20, 10, 5, 15}
Output : prefixSum[] = {10, 30, 40, 45, 60}
We use this concept in many problems in long run. So, be sure you learn this.🤗
CODE:- Code for Prefix sum array
Bonus concepts and problems
Now, try solving problems after learning all these concepts and let me know your approach and views.🤗
Thank you! Will meet you all in my next article.😍