The longest sub-array with switching elements

Viewed 5490

An array is called "switching" if the odd and even elements are equal.

Example:

[2,4,2,4] is a switching array because the members in even positions (indexes 0 and 2) and odd positions (indexes 1 and 3) are equal.

If A = [3,7,3,7, 2, 1, 2], the switching sub-arrays are:

== > [3,7,3,7] and [2,1,2]

Therefore, the longest switching sub-array is [3,7,3,7] with length = 4.

As another example if A = [1,5,6,0,1,0], the the only switching sub-array is [0,1,0].

Another example: A= [7,-5,-5,-5,7,-1,7], the switching sub-arrays are [7,-1,7] and [-5,-5,-5].

Question:

Write a function that receives an array and find its longest switching sub-array.

I would like to know how you solve this problem and which strategies you use to solve this with a good time complexity?

5 Answers

I am assuming that the array is zero indexed .

if arr.size <= 2
    return arr.size
else 
   ans = 2
   temp_ans = 2 // We will update ans when temp_ans > ans;
   for i = 2; i < arr.size ; ++i
       if arr[i] = arr[i-2]
            temp_ans = temp_ans + 1;
       else
            temp_ans = 2;
       ans = max(temp_ans , ans);
   return ans;

I think this should work and I don't think it needs any kind of explanation .
Example Code

 private static int solve(int[] arr){
        if(arr.length == 1) return 1;
        int even = arr[0],odd = arr[1];
        int start = 0,max_len = 0;
        for(int i=2;i<arr.length;++i){
            if(i%2 == 0 && arr[i] != even || i%2 == 1 && arr[i] != odd){
                 max_len = Math.max(max_len,i - start);
                 start = i-1;
                 if(i%2 == 0){
                     even = arr[i];
                     odd = arr[i-1];
                 }else{
                     even = arr[i-1];
                     odd = arr[i];
                 }
            }
        }     


        return Math.max(max_len,arr.length - start);
    }
  • It's like a sliding window problem.
  • We keep track of even and odd equality with 2 variables, even and odd.
  • Whenever we come across a unmet condition, like index even but not equal with even variable and same goes for odd, we first
    • Record the length till now in max_len.
    • Reset start to i-1 as this is need incase of all elements equal.
    • Reset even and odd according to current index i to arr[i] and arr[i-1] respectively.

Demo: https://ideone.com/iUQti7

I didn't analyse the time complexity, just wrote a solution that uses recursion and it works (I think):

public class Main
{
    public static int switching(int[] arr, int index, int end)
    {
        try
        {
            if (arr[index] == arr[index+2])
            {
                end = index+2;
                return switching(arr, index+1, end);
            }
            
        } catch (Exception e) {}
        
        return end;
    }
    
    public static void main(String[] args)
    {
        //int[] arr = {3,2,3,2,3};
        //int[] arr = {3,2,3};
        //int[] arr = {4,4,4};
        int[] arr = {1,2,3,4,5,4,4,7,9,8,10};
        
        int best = -1;
        
        for (int i = 0; i < arr.length; i++) 
                best = Math.max(best, (switching(arr, i, 0) - i));
        
        System.out.println(best+1); // It returns, in this example, 3
    }

}


int switchingSubarray(vector<int> &arr, int n) {
if(n==1||n==2) return n;
int i=0;
int ans=2;
int j=2;
while(j<n)
{
    if(arr[j]==arr[j-2]) j++;
    else
    {
        ans=max(ans,j-i);
        i=j-1;
        j++;
    }
}
ans=max(ans,j-i);
return ans;
}

Just using sliding window technique to solve this problems as element at j and j-2 need to be same. Try to dry run on paper u will surely get it .

# Switching if numbers in even positions equal to odd positions find length of longest switch in continuos sub array
 def check(t):
     even = []
     odd = []
     i = 0
     while i < len(t):
         if i % 2 == 0:
             even.append(t[i])
         else: 
             odd.append(t[i])
         i += 1

     if len(set(even)) == 1 and len(set(odd)) == 1:
         return True
     else:
         return False

 def solution(A):
     maxval = 0
     if len(A) == 1:
         return 1
     for i in range(0, len(A)):
         for j in range(0, len(A)):
             if check(A[i:j+1]) == True:
                 val = len(A[i:j+1])
                 print(A[i:j+1])
                 if val > maxval:
                     maxval = val
     return maxval
 A = [3,2,3,2,3]
 A = [7,4,-2,4,-2,-9]
 A=[4]
 A = [7,-5,-5,-5,7,-1,7]
 print(solution(A))
Related