Friday, July 19, 2024

Interview Question Preperation : Find longest subarray whose sum is equal to K

Software Engineering Practice interview question

Given a array of N elements. Find the length of Longest Subarray whose sum is equal to given K.

 This I believe is one of the most basic Problem Solving(PS) question, which I have found most people get wrong. 

So I wont keep you holding for long, and here is the solution: 



//Returns -1 when no sub-array has sum equal to k. 

int longestSubarrayWithSumK(vector<int> inputArray, long k)     

int l = 0,  max_len = -1, n = inputArray.size();    

    for(int r = 0; r < n; r++){

        long long running_sum= running_sum+ inputArray[r];


        //when the running_sum overshoots the k, try to get it under K and note what the index untill where you are reducing it. 

        while(running_sum> k){

            running_sum -= inputArray[l];

            l++;

        }


     //Once we get the running sum equal to K, check if the current running index length of subarray is more than previously seen subarray length

        if (running_sum== k){

            max_len = max(max_len, r - l + 1);

        }    

    }

        return max_len;

}

Wednesday, July 03, 2024

c # : Tuple Class to store / hold together loosely associated/related items

 Many a  time, you would wonder how to return a pair of objects (not necessarily just 2, but 3,4,5) from a a function and simply creating a new Class to hold together those objects does not make sense / justifiable. 


In such cases, you can make use the Tuple Class in C#, which is  versatile class for the same purpose. 


public (int diameter, double circumference, double area) GetCircleMetaData(int radius) {

    const double PI = 3.1415; var diameter = radius * 2; var circumference = PI * diameter; var area = PI * radius * radius; return (diameter, circumference, area); }


var (d, c, a) = GetCircleMetaData(9);

Interview Question Preperation : Find longest subarray whose sum is equal to K

Software Engineering Practice interview question Given a array of N elements. Find the length of Longest Subarray whose sum is equal to give...