Posts

Showing posts with the label Day8

Check if array elements are consecutive

Input: {5,4,1,2,3} Output: yes Explanation: Max element is 5 and min element id 1, Array contains all elements from 1 to 5 Input: {2,1,0,-3,-2,-1} Output: yes Explanation: Array contains elements from -3 to 2. Concept used: If the array elements are consecutive and distinct then the array is in AP. So we compare array sum with AP sum. ap_sum = n/2 * [2a +(n-1)*d] where d = 1, since elements are consecutive. Code: import java.util.*; public class Solution {          public static void main(String[] args) {                 int[] a = {5, 4, 2, 1, 3};         int n = a.length;         int sum = 0;         boolean result = false;                  int first = a[0];         for(int i=1; i<n; i++){             if(a[i]<first) ...

Segregate even and odd numbers

Input = {12, 34, 45, 9, 8, 90, 3} Output = {12, 34, 8, 90, 45, 9, 3} Method1: O(n) time Keep incrementing left till we have even number. Keep incrementing right till we have odd number. Swap left and right if left less than right. Code: import java.util.*; public class Solution {          public static void main(String[] args) {                 int[] a = {12, 34, 45, 9, 8, 90, 3};         int n = a.length;         int left = 0, right = n-1;                  while(left<right){             while(a[left]%2 == 0 && left< right){                 left++;             }             while(a[right]%2 !=0 && left< right){               ...

Find subarray with given sum

Image
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Ouptut: Sum found between indexes 2 and 4 Input: arr[] = {10, 2, -2, -20, 10}, sum = -10 Ouptut: Sum found between indexes 0 to 3 Input: arr[] = {-10, 0, 2, -2, -20, 10}, sum = 20 Ouptut: No subarray with given sum exists Naive Solution:    We pick elements one by one in outer loop and find its sum with other elements to its right till we get the given sum. Code: import java.util.*; public class Solution {          public static void main(String[] args) {                 int[] a = {10, 2, -2, -20, 10};         int n = a.length;         int sum = -10, currsum = 0;         int index1 = -1, index2 = -1;                  for(int i=0; i<n; i++){             currsum = a[i];           ...