Pages

Thursday 14 September 2017

Check Parentheses are balanced in the given string/array of characters - Java (Using Data Structure - Stack)

package com.belson.codersbeat;

public class ParanthesesMatch {

static class Stack{
int top = -1;
char[] chstack=new char[100];
    void push(char x){
    if(top==99)
    System.out.println("Stack full");
    else
    chstack[++top]=x;
}
   
    char pop(){
    if(top==-1){
    System.out.println("Stack underflow error");
    return '\0';
    }
    else
    {
    char popstack = chstack[top];
    top--;
    return popstack;
    }
   
   }
   
    boolean isEmpty(){
    return (top == -1) ? true : false ;
   }
}

static boolean isMatched(char ch1,char ch2){
if( (ch1=='{' && ch2=='}') || (ch1=='(' && ch2==')') || (ch1=='[' && ch2==']') )
return true;
else
return false;
}

static boolean areBalanced(char[] ch){
Stack st = new Stack();

for(int i=0;i<ch.length;i++){
if(ch[i]=='{' || ch[i]=='(' || ch[i]=='[')
st.push(ch[i]);

if(ch[i]=='}' || ch[i]==')' || ch[i]==']')
{
if(st.isEmpty() || !isMatched(st.pop(),ch[i]))
return false;
}
}

if(st.isEmpty())
return true;
else
return false;
}

public static void main(String[] args) {
String s = "{([])}";
char[] ch = s.toCharArray();

if(areBalanced(ch))
System.out.println("Balanced");
else
System.out.println("Not Balanced");
}

}

Output :

Balanced

Wednesday 7 June 2017

For the given position find the perfect square else make it to next nearest perfect square,then make that to first element and align remaining in ascending order

public class PerfectSquare {

public static void main(String[] args) {
int a[] = {3,12,61,22,78,7};
int sq=0,sqt=0,pos,fp,tmp;
Scanner s = new Scanner(System.in);
System.out.println("Enter the position :");
pos = s.nextInt();
        
/*Making perfect square*/
while(sq != a[pos]){  
        sqt =(int) Math.sqrt(a[pos]);
        sq  = sqt * sqt;
       
        if(sq!=a[pos])
          a[pos]++;
        }

/*Swapping perfect square element to first position*/
fp=a[0];
a[0]=a[pos];
a[pos]=fp;

/*Sorting elements in ascending order - Bubble sort*/
for(int j=0;j<a.length;j++){
for(int k=0;k<a.length;k++){
if(j==0 || k==0)
continue;
if(a[k]>a[j]){
tmp  = a[k];
a[k] = a[j];
a[j] = tmp;
}
}
}

for(int i:a){
System.out.print(i+" ");
}
s.close();
}
}

Output:

Enter the position :
3

25 3 7 12 61 78 

Friday 2 June 2017

Order the elements of array in consecutive maximum and minimum sequence

public class FirstMaxFirstMin {
void rearrange(int arr[], int n)
{
   // Auxiliary array to hold modified array
   int temp[] = new int[n];
 
   // Indexes of smallest and largest elements
   // from remaining array.
   int small=0, large=n-1;
 
   // To indicate whether we need to copy remaining
   // largest or remaining smallest at next position
   boolean flag = true;
 
   // Store result in temp[]
   for (int i=0; i<n; i++)
   {
       if (flag)
           temp[i] = arr[large--];
       else
           temp[i] = arr[small++];
 
       flag = !flag;
   }
 
   // Copy temp[] to arr[]
   for (int i=0; i<n; i++)
       arr[i] = temp[i];
}

public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = arr.length;
        
FirstMaxFirstMin f=new FirstMaxFirstMin();
 
System.out.println("Original Array");
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");

f.rearrange(arr, n);

System.out.println("\nModified Array");
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}

}

Output:

Original Array
1 2 3 4 5 6 7 8 9 
Modified Array
9 1 8 2 7 3 6 4 5 

Merge Two arrays without duplicates and sort the array to ascending order

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MergeArrays {

public static void main(String[] args) {
int a[]={1,2,3,4};
int b[]={10,9,8,7,5,4,0,-6,0,0,0};
int count = 0,temp;

Set<Integer> nodup = new HashSet<Integer>();

for(int i=0;i<a.length;i++){
nodup.add(a[i]);
}
for(int i=0;i<b.length;i++){
nodup.add(b[i]);
}

int f[] = new int[nodup.size()];
int z = 0;

Iterator<Integer> it = nodup.iterator();
while(it.hasNext()){
f[z]=it.next();
z++;
}

for(int l=0;l<f.length;l++){
for(int m=0;m<f.length;m++){
if(f[l]<f[m]){
temp=f[l];
f[l]=f[m];
f[m]=temp;
}
}
}

for(int k=0;k<f.length;k++){
System.out.print(f[k]+" ");
}

}
}

Output:

-6 0 1 2 3 4 5 7 8 9 10 

Pascal's Triangle using Java

import java.util.Scanner;

public class PascalsTriangle {

public static void main(String[] args) {
int rows,coef=1,space,i,j;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of rows : ");
rows = s.nextInt();
for(i=0;i<rows;i++)
{
for(space=1;space<=rows-i;space++)
{
System.out.print("  ");
}

for(j=0;j<=i;j++)
{
if(i==0 || j==0){
coef=1;
}else{
coef=coef*(i-j+1)/j;
}

System.out.printf("%4d",coef);
}
System.out.println();
}
        s.close();
}
}

Output:

Enter the number of rows : 
5
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1


Monday 15 May 2017

Web Service Components

There are three major web service components.
  1. SOAP
  2. WSDL
  3. UDDI

SOAP

  • SOAP is an acronym for Simple Object Access Protocol.
  • SOAP is a XML-based protocol for accessing web services.
  • SOAP is a W3C recommendation for communication between applications.
  • SOAP is XML based, so it is platform independent and language independent. In other words, it can be used with Java, .Net or PHP language on any platform.

WSDL

  • WSDL is an acronym for Web Services Description Language.
  • WSDL is a xml document containing information about web services such as method name, method parameter and how to access it.
  • WSDL is a part of UDDI. It acts as a interface between web service applications.
  • WSDL is pronounced as wiz-dull.

UDDI

  • UDDI is an acronym for Universal Description, Discovery and Integration.
  • UDDI is a XML based framework for describing, discovering and integrating web services.
  • UDDI is a directory of web service interfaces described by WSDL, containing information about web services.

Types of Web Services

There are mainly two types of web services.
  1. SOAP web services.
  2. RESTful web services.
types of web services

What is Web Service

Web Service can be defined by following ways:
  • is a client server application or application component for communication.
  • method of communication between two devices over network.
  • is a software system for interoperable machine to machine communication.
  • is a collection of standards or protocols for exchanging information between two devices or application.
Let's understand it by the figure given below:

web services

As you can see in the figure, java, .net or PHP applications can communicate with other applications through web service over the network. For example, java application can interact with Java, .Net and PHP applications. So web service is a language independent way of communication.

RESTful Web Services

REST stands for REpresentational State Transfer.

REST is an architectural style not a protocol.

Advantages of RESTful Web Services

Fast: RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less bandwidth and resource.

Language and Platform independent: RESTful web services can be written in any programming language and executed in any platform.

Can use SOAP: RESTful web services can use SOAP web services as the implementation.

Permits different data format: RESTful web service permits different data format such as Plain Text, HTML, XML and JSON.

Page - 1

Thursday 11 May 2017

Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)

In this article following Data Structures are discussed.
5. Binary Tree
6. Binary Search Tree
7. Binary Heap
9. Hashing
Binary Tree

Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures.
A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. It is implemented mainly using Links.
Binary Tree Representation: A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL. A Binary Tree node contains following parts.
1. Data
2. Pointer to left child
3. Pointer to right child
A Binary Tree can be traversed in two ways:
Depth First Traversal: Inorder (Left-Root-Right), Preorder (Root-Left-Right) and Postoder (Left-Right-Root)
Breadth First Traversal: Level Order Traversal
Binary Tree Properties:
The maximum number of nodes at level ‘l’ = 2l-1.

Maximum number of nodes = 2h – 1.
Here h is height of a tree. Height is considered 
as is maximum number of nodes on root to leaf path

Minimum possible height =  ceil(Log2(n+1))   

In Binary tree, number of leaf nodes is always one 
more than nodes with two children.

Time Complexity of Tree Traversal: O(n)
Examples : One reason to use binary tree or tree in general is for the things that form a hierarchy. They are useful in File structures where each file is located in a particular directory and there is a specific hierarchy associated with files and directories. Another example where Trees are useful is storing heirarchical objects like JavaScript Document Object Model considers HTML page as a tree with nesting of tags as parent child relations.
Binary Search Tree

In Binary Search Tree is a Binary Tree with following additional properties:
1. The left subtree of a node contains only nodes with keys less than the node’s key.
2. The right subtree of a node contains only nodes with keys greater than the node’s key.
3. The left and right subtree each must also be a binary search tree.
Time Complexities:
Search :  O(h)
Insertion : O(h)
Deletion : O(h)
Extra Space : O(n) for pointers

h: Height of BST
n: Number of nodes in BST

If Binary Search Tree is Height Balanced, 
then h = O(Log n) 

Self-Balancing BSTs such as AVL Tree, Red-Black
Tree and Splay Tree make sure that height of BST 
remains O(Log n)
BST provide moderate access/search (quicker than Linked List and slower than arrays).
BST provide moderate insertion/deletion (quicker than Arrays and slower than Linked Lists).
Examples : Its main use is in search application where data is constantly entering/leaving and data needs to printed in sorted order. For example in implementation in E- commerce websites where a new product is added or product goes out of stock and all products are lised in sorted order.
Binary Heap

A Binary Heap is a Binary Tree with following properties.
1) It’s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to Min Heap. It is mainly implemented using array.
Get Minimum in Min Heap: O(1) [Or Get Max in Max Heap]
Extract Minimum Min Heap: O(Log n) [Or Extract Max in Max Heap]
Decrease Key in Min Heap: O(Log n)  [Or Extract Max in Max Heap]
Insert: O(Log n) 
Delete: O(Log n)
Example : Used in implementing efficient priority-queues, which in turn are used for scheduling processes in operating systems. Priority Queues are also used in Dijstra’s and Prim’s graph algorithms.
Order statistics: The Heap data structure can be used to efficiently find the k’th smallest (or largest) element in an array.
Heap is a special data structure and it cannot be used for searching of a particular element.
Hashing
Hash Function: A function that converts a given big input key to a small practical integer value. The mapped integer value is used as an index in hash table. A good hash function should have following properties
1) Efficiently computable.
2) Should uniformly distribute the keys (Each table position equally likely for each key)
Hash Table: An array that stores pointers to records corresponding to a given phone number. An entry in hash table is NIL if no existing phone number has hash function value equal to the index for the entry.
Collision Handling: Since a hash function gets us a small number for a key which is a big integer or string, there is possibility that two keys result in same value. The situation where a newly inserted key maps to an already occupied slot in hash table is called collision and must be handled using some collision handling technique. Following are the ways to handle collisions:
Chaining:The idea is to make each cell of hash table point to a linked list of records that have same hash function value. Chaining is simple, but requires additional memory outside the table.
Open Addressing: In open addressing, all elements are stored in the hash table itself. Each table entry contains either a record or NIL. When searching for an element, we one by one examine table slots until the desired element is found or it is clear that the element is not in the table.
Space : O(n)
Search    : O(1) [Average]    O(n) [Worst case]
Insertion : O(1) [Average]    O(n) [Worst Case]
Deletion  : O(1) [Average]    O(n) [Worst Case]
Hashing seems better than BST for all the operations. But in hashing, elements are unordered and in BST elements are stored in an ordered manner. Also BST is easy to implement but hash functions can sometimes be very complex to generate. In BST, we can also efficiently find floor and ceil of values.
Example : Hashing can be used to remove duplicates from a set of elements. Can also be used find frequency of all items. For example, in web browsers, we can check visited urls using hashing. In firewalls, we can use hashing to detect spam. We need to hash IP addresses. Hashing can be used in any situation where want search() insert() and delete() in O(1) time.

Overview of Data Structures | Set 1 (Linear Data Structures)

A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Below is an overview of some popular linear data structures.
1. Array
2. Linked List
3. Stack
4. Queue
Array

Array is a data structure used to store homogeneous elements at contiguous locations. Size of an array must be provided before storing data.
Let size of array be n.
Accessing Time: O(1) [This is possible because elements
                      are stored at contiguous locations]   
Search Time:   O(n) for Sequential Search: 
               O(log n) for Binary Search [If Array is sorted]
Insertion Time: O(n) [The worst case occurs when insertion 
                     happens at the Beginning of an array and 
                     requires shifting all of the elements]
Deletion Time: O(n) [The worst case occurs when deletion 
                     happens at the Beginning of an array and 
                     requires shifting all of the elements]
Example : For example, let us say, we want to store marks of all students in a class, we can use an array to store them. This helps in reducing the use of number of variables as we don’t need to create a separate variable for marks of every subject. All marks can be accessed by simply traversing the array.
Linked List

A linked list is a linear data structure (like arrays) where each element is a separate object. Each element (that is node) of a list is comprising of two items – the data and a reference to the next node.
Types of Linked List :
1. Singly Linked List : In this type of linked list, every node stores address or reference of next node in list and the last node has next address or reference as NULL. For example 1->2->3->4->NULL
2. Doubly Linked List : In this type of Linked list, there are two references associated with each node, One of the reference points to the next node and one to the previous node. Advantage of this data structure is that we can traverse in both the directions and for deletion we don’t need to have explicit access to previous node. Eg. NULL<-1<->2<->3->NULL
3. Circular Linked List : Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. Advantage of this data structure is that any node can be made as starting node. This is useful in implementation of circular queue in linked list. Eg. 1->2->3->1 [The next pointer of last node is pointing to the first]
Accessing time of an element : O(n)
Search time of an element : O(n)
Insertion of an Element : O(1) [If we are at the position 
                                where we have to insert 
                                an element] 
Deletion of an Element : O(1) [If we know address of node
                               previous the node to be 
                               deleted] 
Example : Consider the previous example where we made an array of marks of student. Now if a new subject is added in the course, its marks also to be added in the array of marks. But the size of the array was fixed and it is already full so it can not add any new element. If we make an array of a size lot more than the number of subjects it is possible that most of the array will remain empty. We reduce the space wastage Linked List is formed which adds a node only when a new element is introduced. Insertions and deletions also become easier with linked list.
One big drawback of linked list is, random access is not allowed. With arrays, we can access i’th element in O(1) time. In linked list, it takes Θ(i) time.
Stack

A stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added. In stack both the operations of push and pop takes place at the same end that is top of the stack. It can be implemented by using both array and linked list.
Insertion : O(1)
Deletion :  O(1)
Access Time : O(n) [Worst Case]
Insertion and Deletion are allowed on one end. 
Example : Stacks are used for maintaining function calls (the last called function must finish execution first), we can always remove recursion with the help of stacks. Stacks are also used in cases where we have to reverse a word, check for balanced parenthesis and in editors where the word you typed the last is the first to be removed when you use undo operation. Similarly, to implement back functionality in web browsers.
Queue

A queue or FIFO (first in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: enqueue, the process of adding an element to the collection.(The element is added from the rear side) and dequeue, the process of removing the first element that was added. (The element is removed from the front side). It can be implemented by using both array and linked list.
Insertion : O(1)
Deletion  : O(1)
Access Time : O(n) [Worst Case]
Example : Queue as the name says is the data structure built according to the queues of bus stop or train where the person who is standing in the front of the queue(standing for the longest time) is the first one to get the ticket. So any situation where resources are shared among multiple users and served on first come first server basis. Examples include CPU scheduling, Disk Scheduling. Another application of queue is when data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.
Circular Queue The advantage of this data structure is that it reduces wastage of space in case of array implementation, As the insertion of the (n+1)’th element is done at the 0’th index if it is empty.

Print the word with odd letters (Asked in Zoho Interview | Set 1 Question 3)

1. Print the word with odd letters as
P         M
 R      A
   O  R
     G
  O    R
 R       A
P          M 

#include<stdio.h>
#include<string.h>
int main()
{
char s[10]="PROGRAM",s1[10];
int l,i,j;
//scanf("%s",&s);
strcpy(s1,s);
//strrev(s1);
l=strlen(s);
for(i=0;i<l;i++)
{
for(j=0;j<l;j++)
{
if(i==j)
  printf("%c",s[i]);
else if(i+j==l-1)
  printf("%c",s1[i]);
if(j==l-1)
  printf("\n");
else
  printf(" ");
}
}
return 0;
}

input:

PROGRAM


output:


P      P
 R    R 
  O  O  
   G   
  R  R  
 A    A 
M      M

Wednesday 10 May 2017

Nested printf (printf inside printf) in C (Asked in Zoho Interview)

Predict the output of the following C program with a printf inside printf.
#include<stdio.h>
  
int main()
{
   int x = 1987;
   printf("%d", printf("%d", printf("%d", x)));
   return(0);
}

Output :

198741
Explanation :
1. Firstly, the innermost printf is executed which results in printing 1987
2. This printf returns total number of digits in 1987 i.e 4. printf() returns number of characters successfully printed on screen. The whole statement reduces to :
printf("%d", printf("%d", 4));

3. The second printf then prints 4 and returns the total number of digits in 4 i.e 1 (4 is single digit number ).
4. Finally, the whole statement simply reduces to :

printf("%d", 1);

5. It simply prints 1 and output will be :
Output:

198741
So, when multiple printf’s appear inside another printf, the inner printf prints its output and returns length of the string printed on the screen to the outer printf.                                                                     

Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...