Arrays Flashcards
how to insert an element in a array ?
there are two ways to insert an element in a array.
1. add an element ‘element’ at k position. In this case you have to first check if the index k is smaller than the length of the array. then you can easily add the element at arr[k] = element; after shifting all the elements to the right.
2. add an element at the end of the array: In this case, first check if the postion at which you want to add the element is not greater than the length of the array. then just add the element at arr[pos] = element;
How to rotate an array. Explain the approach using temp array.
- first, make a temp array of size equal to the original array.
- Then, copy all the elements from the d(the index from which to rotate the array) to n-1 in the temp array and also keep an variable k to keep track of the last index in the temp array.
- Now only d elements are left in the original array. copy all the leftout elements to the temp array from the index 0 to d. add elements from the index k to the end of the original array.
- copy the elements from temp array to original array if you want or just return the temp array.
time: O(n)
space: O(n)
how to rotate an array by rotating elements one by one ?
- In this approach, first you have to keep an variable to track the first element in the array and then left shift all the elements of the array.
- Then, simply add the variable to the last of the array.
- Repeat this whole process for d times.
- it will take two nested loops to work. Outer loop will keep the track of d and inner loop is for the shifting.
time: O(n*d)
space: O(1)
how to rotate an array using the juggling algorithm ?
- Make a reverse method that can reverse the elements of an array. This method takes three arguments:
- the array on which the reverse operation to be performed
- The starting index
- The ending index
- Now, first reverse the elements starting from 0 to d-1.
- Then, reverse the elements from d to n-1.
- Lastly, reverse the whole array i.e, from 0 to n-1.
The final array is the result after rotating the array by d elements.
time: O(n)
space: O(1)
how to reverse an array iteratively ?
1) Initialize start and end indexes as
start = 0, end = N-1
2) In a loop, swap arr[start] with arr[end]
and change start and end as follows :
start = start + 1,
end = end – 1
time: O(N)
space: constant
how to reverse an array recursively ?
1) Initialize start and end indexes as
start = 0, end = n-1
2) Swap arr[start] with arr[end]
3) Recursively call reverse for rest of the array. for eg.
return reverse(arr, start + 1, end - 1)
time: O(N)
space: constant
what is the purpose of using sliding window technique ? or in which situation we use this technique ?
This technique shows how a nested for loop in few problems can be converted to single for loop and hence reducing the time complexity.
how sliding window technique works ?
This technique works in 3 simple steps:
I am demostrating this technique by solving an max sum for k consecutive elements in a array problem.
In this problem, k is the length of sub array for which we have to calculate the sum of elements.
The following steps demostrate the sliding window technique-
1. first, we will calculate the sum of first k elements for which we will iterate from 0 to k and store the sum of elements in window_sum.
2. Then, we will make an element maxSum for tracking the max sum of elements in the array. Now, we will remove the last element after shifting the window to the left and add the latest element to the sum. The current sum would look something like this currentSum += arr[i] + arr[i -k]
3. Lastly, we will compare the current sum with the max sum that we were keeping for checking the max sum of consecutive elements in an array.
time: O(n)
space: constant
How to find the second largest element in an array ?
Firstly, we should find the largest element in the array and then find the second largest element by just excluding the largest element. we can find the largest and second largest in the same traversal of the array.
The condition to find the second largest is: if (inputArray[index] != largest)
How to move zeros to the end in an array ?
To move zeros to the end in an array, we can use two pointer approach
* First pointer will keep track of the non zero elements present in the array and increment only when it encounters a non zero element.
* Second pointer will simply traverse the array and will help in overriding the zero elements to the non zero elements.
* After the whole traversal, the first pointer will become the 1st index for the zero elements present in the array, so we will simply override all the remaining elements by zero.
time: O(N)
space: constant
how to insert an element in the middle of an array ?
To insert an element in the middle of an array, first you have to move all the elements to the right(only if the capacity is not full otherwise just return the original array)
for moving the elements to the right, traverse the array in reverse direction and override the right element to the left element and stop the iteration at the position on which the new element will be inserted
inserting at the end, time: 1
inserting at the begining, time: n
in general insertion time: n
what is the time complexity of insert at the end for a dynamic sized array ?
In general, it is O(1)
time complexity for inserting in an array ?
O(N)
time complexity for searching in an unsorted array ?
O(N)
Time complexity for searching in an sorted array ?
O(logn)
time complexity for deletion in an array ?
O(N)
time complexity to get and update an ith element in an array ?
O(1)
time complexity for insertion and deletion from the end in an array ?
O(1)
how to find immediate greater element than x in an array ?
- first, we make a variable called currentImmediateGreater and set a large value to it.
- Then we will iterate the whole array and check whether currentImmediateGreater is greater that ith element as well as x(the element to check). The condition will look something like this:
if (inputArray[i] > x && currentImmediateGreater > inputArray[i])
After checking this condition, we will simple re initialize the currentImmediateGreater with inputArray[i] found.
find the majoritGiven an array arr[] of size N and two elements x and y, use counter variables to find which element appears most in the array. If both elements have the same frequency, then return the smaller element.
Note: We need to return the element, not its count.y between two elements x and y
- First, make a counter variable to count the number of occurances for both the elements in the array
- if x is encountered then increament the counter and if y is encountered then decreament the counter.
- if counter is positive then, it means x occured more than y and vice versa.
- if counter is zero then, it means both the elements have same occurance and we will return the smallest among them
how to find max and min element in a array ?
- first, assume arr[0] as the max or min element
- traverse the array and compare the current element with the max element, if the current element is greater than maxElement then, assign maxElement with the current element
- do the same for minElement
how to reverse an array without using temporary array?
- for this we will first make a temporary variable temp and use it swap the elements in the array
- we will traverse the array to it’s half size and keep swapping the elements until we reach the half the length
how to check if a char array is palindrome or not using recursion ?
There would be three conditions to check whether the array is palindrome or not.
- check if there is only one character in the array, it means it is palindrome
- check if the first and last character matches or not, if not then it is not palindrome
- check the substring or subarray by calling the method recusively as
~~~
checkPalindrome(string[], start + 1, end - 1)
~~~
Give brute force solution
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Approach 1: Brute Force
Algorithm
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target−x.
class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[j] == target - nums[i]) { return new int[] { i, j }; } } } // If no valid pair is found, return an empty array instead of null return new int[] {}; } }
Complexity Analysis
Time complexity: O(n
2
).
For each element, we try to find its complement by looping through the rest of the array which takes O(n) time. Therefore, the time complexity is O(n
2
).
Space complexity: O(1).
The space required does not depend on the size of the input array, so only constant space is used.