Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, September 24, 2018

Number of Subarray with odd sum Floak Intern


This question was asked in FLOAK intern on 23/09/2018.
Basic idea is to store cummutative sum in a hash of size 2 i.e. even and odd subarray 
At the end return multiply of both hash
Wait .. It gave me TLE ...
So we need to go with FAST I/O as there are a lot of input and will take time

Java Code:

import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class oddSubarray
 {

    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
   public static long subarray(int a[],int n)
{
long hash[]=new long[2];
hash[0]=1;
hash[1]=0;
int val=0;
for(int i=0;i<=n-1;++i)
{
  val=((val+a[i])%2+2)%2;
  ++hash[val];
}
return hash[0]*hash[1];
}
public static void main (String[] args)
{
        FastReader s=new FastReader();
        int t = s.nextInt();
while(t-->0)
{

    int n = s.nextInt();
    int arr[]=new int[n];
    for(int i=0;i<n;++i)
    arr[i]=s.nextInt(); 
    System.out.println(subarray(arr,n));
}
}
}

0 Comments:

Post a Comment

Stats