Thursday 22 February 2018

Check for balanced parentheses in an expression using Stack class of Java

import java.util.*;
class Solution{
 
   public static void main(String []argh)
   {
      Scanner sc = new Scanner(System.in);
      Stack<Character> stack = new Stack<>();
      while (sc.hasNext()) {
         String input=sc.next();
          for(int i=0;i<input.length();i++)
          {
              char c=input.charAt(i);
           
              if(c=='(' || c=='{' || c=='[')
                 stack.push(c);
             
             
              else if(!(stack.isEmpty())){
                    if((c==')' && stack.peek()=='(' )|| (c=='}' && stack.peek()=='{') || c==']' && stack.peek()=='[')
                        stack.pop();
                 
              }
              else stack.push(c);
             
          }
         
          if(stack.empty())
              System.out.println("true");
          else
              System.out.println("false");
          stack.clear();// IMPORTANT :)
      }
     
   
   }
}

Wednesday 21 February 2018

Two Dimensional Dynamic Array in Java

/*Coded By-Shivam Tripathi*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        List<ArrayList<Integer>> ar=new ArrayList<ArrayList<Integer>>();
        int n=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            ar.add(new ArrayList<Integer>());
        }
        for(int i=0;i<n;i++)
        {
            int d=sc.nextInt();
            for(int j=0;j<d;j++)
            {
                int num=sc.nextInt();
                ar.get(i).add(num);
            }
        }
         int q = sc.nextInt();
        for(int i=0; i<q; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
           
            try {
                System.out.println(ar.get(x-1).get(y-1));
            } catch(Exception e) {
                System.out.println("ERROR!");
            }
        }
       
       
    }
}

Wednesday 14 February 2018

Finding Square Root of a number without using in-built function

Using Binary Search
float sqrt(n) {
    low = 0.0;
    high = (float)n+1;
    while ((high-low) > 0.00001) {
        mid = (low+high) / 2;
        if (mid*mid < n) {
            low = mid;
        }
        else {
            high = mid;
        }
    }
    return low;
}