Index of an Extra Element
In this page, we will solve the problem of determining the index of the extra element in the array.
Problem Descriptionβ
You have given two sorted arrays arr1[] & arr2[] of distinct elements. The first array has one element extra added in between. Return the index of the extra element.
Note: 0-based indexing is followed.
Examplesβ
Example 1:
Input: n = 7, arr1[] = {2,4,6,8,9,10,12}, arr2[] = {2,4,6,8,10,12}
Output: 4
Explanation: In the first array, 9 is extra added and it's index is 4.
Example 2:
Input: n = 6, arr1[] = {3,5,7,8,11,13}, arr2[] = {3,5,7,11,13}
Output: 3
Explanation: In the first array, 8 is extra and it's index is 3.
Constraintsβ
- , where is number of nodes
Solutionβ
Intuition and Approachβ
This problem can be solved by iterating over the array by runnig the loop from o to the length of the smallest array
- Inorder Traversal
Approach: Inorder Traversalβ
- Run a for loop from 0 to length of the smallest array.
- If at any point in loop the element on ith index of both arrays are different then return the index as it is the answer
- If loop runs completely and didn't terminate this means the last index of the largest array is the answer and return that index
Code in Pythonβ
class Solution:
def findExtra(self,n,a,b):
for i in range(min(len(a),len(b))):
if a[i]!=b[i]:return i
return i+1
Complexity Analysisβ
- Time Complexity:
- Space Complexity: