Thursday, October 24, 2019

Finding Maximum and Minimun values from an Array



Program

package minmax;

public class MinMax
{
    public static void main(String[] args)
    {
        int a[] = {10,324,45,90,9808};
        int min = a[0];
        int max = a[0];
        for(int i =  0 ;  i <  a.length; i++)
        {
            if(a[i] >  max)
                max = a[i];
            if(a[i] < min)
                min = a[i];
        }
        System.out.println("Max value " + max);
        System.out.println("Min value " + min);
    }
   
}


Video explanation



Wednesday, October 23, 2019

Area and Perimeter of Rectangle

 

Question

You need to read two side values S1 and S2 from the user and calculate the area & perimeter of the rectangle using their side values and print the same.

Program

package area;
import java.util.Scanner;

public class Area
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        long s1 = in.nextLong();
        long s2 = in.nextLong();
        //long area = s1 * s2;
        //long perimeter = 2 * (s1 + s2);
        System.out.println("Area " + (s1 * s2));
        System.out.println("Perimeter " + (2*(s1 + s2)));
    }
   
}

Video explanation



Tuesday, October 22, 2019


Question

In this challenge, you must read an integer, a double, a string and a character from keyboard, then print the values

Program

package inout;

import java.util.Scanner;

public class Inout
{
    public static void main(String[] args)
    {
        Scanner in =  new Scanner(System.in);
        String s = in.nextLine();
        char c = in.nextLine().charAt(0);
        int x = in.nextInt();
        double d = in.nextDouble();
        System.out.println("Integer- " +  x);
        System.out.println("Double- " +  d);
        System.out.println("String- " + s);
        System.out.println("Char- " + c);
    }
   
}

Video explanation



Simple use of if - else

Question

Given an integer,n, perform the following conditional operations,

If n is odd, print Good

If n is even and in the inclusive range of 2 to 5, print Not Good

If n is even and in the inclusive range of 6 to 20, print Good

If n is even and greater than 20, print Not Good

Program

package ifelse;
import java.util.Scanner;
public class IfElse
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        if(N%2==1)
        {
            System.out.println("Good");
        }
        else
        {
            if(N >= 2 && N <= 5)
                System.out.println("Not Good");
            else if(N >= 6 && N <= 20)
                System.out.println("Good");
            else if(N > 20)
                System.out.println("Not Good");
        }
    }
}

Video  explanation




Sunday, October 20, 2019

Pattern printing 1

Expected pattern

 

* * * *
* * * *
* * * *
* * * *
* * * *

Program

#include<iostream>
using namespace std;
int main()
{
    for(int i = 1; i <= 5; i++)
    {
        for(int j = 1; j<= 4; j++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
}

Video explanation

 

 

Sum of digits of a number



Program  

package sumofdigits;

public class SumOfDigits
{
    public static void main(String[] args)
    {
        int n = 34;
        int sum = 0;
        while(n > 0)
        {
            int temp = n % 10;
            sum = sum + temp;
            n = n / 10;
        }
        System.out.println(sum);
    }
   
}

Video  explanation



Count the number of Digits of a Number



Program

package digits;

public class Digits
{
    public static void main(String[] args)
    {
        int n = 34243;
        int count = 0;
        while(n > 0)
        {
            n = n / 10;
            count++;
        }
        System.out.println(count);
    }
}

Video explanation


Thursday, October 17, 2019

Fibonacci Series



Program


package fibo;
public class Fibo
{
    public static void main(String[] args)
    {
        int n = 10;
        int f = 1,s = 1,t;
        System.out.println(f);
        System.out.println(s);
        for(int i = 3; i<= n; i++)
        {
            t = f + s;
            System.out.println(t);
            f = s;
            s = t;
        }
    }
   
}

Video explanation

Find Factorial of a number



Program


package fact;

public class Fact
{
    public static void main(String[] args)
    {
        int n= 5;
        int fact = 1, i;
        for (i=2; i<=n; i++)
        {
            fact = fact * i;
        }
        System.out.println(fact);
    }
}


Video explanation



Check if a given year is Leap Year



Program


package leap.year;
import java.util.*;
public class LeapYear
{
    public static void main(String[] args) 
    {
        int year = 1996;
        // If a year is multiple of 400,
        // then it is a leap year
        if (year % 400 == 0)           
            System.out.println("Leap year");
        // Else If a year is muliplt of 100,
        // then it is not a leap year
        else if (year % 100 == 0)     
            System.out.println("Not leap year");
        // Else If a year is muliplt of 4,
        // then it is a leap year
        else if (year % 4 == 0)  
            System.out.println("Leap year");
    }
   
}

Video explanation



C++ program to Swap two numbers (Using extra variable)



Program 

#include<iostream>
using namespace std;

int main()
{
    int a = 105, b = 2;
    int temp;
    cout<<"Before swap "<<a<<" "<<b<<endl;
    temp = a;
    a = b;
    b =temp;

    cout<<"After swap "<<a<<" "<<b;

}

Video explanation


C++ program to find if a number is ODD or EVEN

Program

#include<iostream>
using namespace std;

int main()
{
    int number = 36;

    if(number % 2 == 0)
    {
        cout<<"Number is even";
    }
    else
    {
        cout<<"Number is Odd";
    }
}

Video explanation


C++ program to find Quotient and Remainder



 Program


#include<iostream>
using namespace std;

int main()
{
    int a = 15, b = 3;
    int quotient, remainder;

    quotient = a / b;
    remainder = a % b;

    cout<<"Quotient is "<<quotient<<endl;
    cout<<"Remainder is "<<remainder;
}

Video explanation

Wednesday, August 21, 2019

Given a string, find its first non-repeating character

Given a string, find the first non-repeating character in it.




Solution:

  • Using Array-
    1.  Create an arrays (count[]) of size 256 (Total ASCII codes).
    2. Read the input string character by character and increament values of count[] at index corresponding to the ASCII value of the current character.
    3. To find the first non-repeating character, again read through the input, character by character and check if it's count is equal to 1 from the count[] array.
    4. If count[] is equal to 1, print character and exit.
    5. Else print no "non repeating character found".
  •  Using HashMap-
    1. Create a HashMap count<Character, Integer>.  
    2. Read the input string character by character,
      • If character already present, increament it's count
      • Else insert the character with count as 1.
    3. To find the first non-repeating character, again read through the input, character by character and check if it's count in the HashMap is equal to 1,
      • If equal to 1, print character and exit.
      • Else print no "non repeating character found".

 

Java code-

Using Array-

public class FirstNonRepeatingCharacterUsingArray
{
    public static void main(String[] args)
    {
        int count[] = new int[256];
        String s = "MuscleJavaMuscle";
        for(int i=0; i<s.length(); i++)
        {
            count[ s.charAt(i) ]++ ;
        }
        System.out.println("First non-repeating character- ");
        for(int i=0; i<s.length(); i++)
        {
            if(count[ s.charAt(i) ] == 1)
            {
                System.out.println(s.charAt(i));
                System.exit(0);     //exit program if required
                                    //output is found
            }
        }
        /*this part of code will run if
        the first non repeating character is not found*/
        System.out.println("Not found");       
    }
}

Using HashMap-

public class FirstNonRepeatingCharUsingHashMap
{
    public static void main(String[] args)
    {
        HashMap<Character, Integer> count = new HashMap<>();
        String s = "MuscleJavaMuscle";
        for(int i=0; i<s.length(); i++)
        {
            if(!count.containsKey(s.charAt(i))) //if not present in
                                                //HashMap
                count.put(s.charAt(i), 1);      //put the char and
                                                //its count as '1'
            else        //if present, increase it count
                count.replace(s.charAt(i),count.get(s.charAt(i))+1);
        }
        //to print
        for(int i=0; i<s.length(); i++)
        {
            if(count.get(s.charAt(i)) == 1)
            {
                System.out.print("First non-repeating "
                        + "character- " + s.charAt(i));
                System.exit(0);
            }
        }
        /*this part of code will run if
        the first non repeating character is not found*/
        System.out.println("Not found");
    }
}

Output-

First non-repeating character- J 

 


Saturday, July 6, 2019

Max distance between same elements using Hashing

Problem Statement:

Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element.

Input:
The first line of input will contain no of test cases T . Then T test cases follow . Each test case contains 2 lines. The first line of each test case contains an integer N denoting the number of elements in the array, the next line contains N space separated integer's.

Output:
For each test case in new line print the Maximum distance between two occurrences of an element

Constraints:
1<=T<=100
1<=N<=1000

Example:
Input
2
6
1 1 2 2 2 1
12
3 2 1 2 1 4 5 8 6 7 4 2

Output
5
10

Explanation
Test case 1:
arr[] = {1, 1, 2, 2, 2, 1}
Max Distance: 5
Distance for 1 is: 5-0 = 5
Distance for 2 is : 4-2 = 2
Max Distance 5

Test case 2:
arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}
Max Distance 10
maximum distance for 2 is 11-1 = 10
maximum distance for 1 is 4-2 = 2
maximum distance for 4 is 10-5 = 5


Solution:


import java.util.Scanner;
import java.util.*;
class Max_Dis_Between_Same_Element
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int t =sc.nextInt();
        while(t>0)
        {
            int n = sc.nextInt();
            int arr[] = new int[n];
            for(int i=0;i<n;i++)
                arr[i] = sc.nextInt();
            MuscleJava g = new MuscleJava();
            System.out.println(g.maxDistance(arr,n));
       
        t--;
        }
    }
}
class MuscleJava
{
    int maxDistance(int arr[], int n)
    {
        int max=0;
        HashMap<Integer,Integer> lastIndex = new HashMap<>();
        HashMap<Integer,Integer> FirstIndex = new HashMap<>();
        for(int i=0; i<n; i++)
        {
            lastIndex.put(arr[i],i);
            if(!FirstIndex.containsKey(arr[i]))
                FirstIndex.put(arr[i],i);
        }
        for(int i=0; i<n; i++)
        {
            int first = FirstIndex.get(arr[i]);
            int last = lastIndex.get(arr[i]);
            if((last - first) > max )
                max = last - first;
        }
        return max;
    }
}
 

Minimum indexed character using Hashing

Problem Statement:


Given a string str and another string patt. Find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print ‘$’.
Input:
The first line of input contains an integer T denoting the number of test cases. Then the description of T test cases follow. Each test case contains two strings str and patt respectively.

Output:
Output the character in patt that is present at the minimum index in str. Print "$" (without quotes) if no character of patt is present in str.

User Task:
The task is to complete the function printMinIndexChar() which finds the character in patt that is present at minimum index in str.

Constraints:
1 <= T <= 105
1 <= |str|, |patt| <= 105

Example:
Input:

2
geeksforgeeks
set
adcffaet
onkl

Output:
e
$

Explanation:
Testcase 1:
e is the character which is present in given patt "geeksforgeeks" and is first found in str "set".


Solution:


import java.io.*;
import java.util.*;
class GFG 
{
    public static void main (String[] args) throws IOException 
    {
       
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
       
        while(t-- > 0)
        {
           
            String str = br.readLine();
            String patt = br.readLine();
            PrintString obj = new PrintString();
            System.out.println(obj.printMinIndexChar(str, patt));
           
        }
       
    }
}

class PrintString
{
       public static String printMinIndexChar(String str, String patt)
    {
        HashMap<Character,Integer> h = new HashMap();
        for(int i=0; i<str.length(); i++)
        {
            if(!h.containsKey(str.charAt(i)))
                h.put(str.charAt(i) , i);
        }
        String min = "$";
        int minIndex = 10000;
        for(int i=0; i<patt.length(); i++)
        {
            if(h.containsKey(patt.charAt(i)))
                if(h.get(patt.charAt(i)) < minIndex)
                {
                    minIndex = h.get(patt.charAt(i));
                    min = patt.charAt(i) + "";
                }
        }
        return min;
    }
   
}