iram company ( through fresherworld 2016, 2017 batch )

iram company ( through fresherworld 2016, 2017 batch )

developer
City Engineering College
Address: Kanakapura Road, Doddakallasandra, Bikasipura, Bengaluru, Karnataka 560062\\

****************************************************************************************
https://www.glassdoor.co.in/Interview/iRam-Technologies-Interview-Questions-E1976877.htm
************************************************************************************************
Time and Distance
Time and Work
Compound Interest
Partnership
Problems on Ages
Clock
Area
Permutation and Combination
Problems on Numbers
Decimal Fraction

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

Iterative Solution

1) Initialize count as 0
2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
a) current = current -> next
b) count++;
4) Return count
Following are C/C++, Java and Python implementations of above algorithm to find count of nodes.

/// Java program to count number of nodes in a linked list

/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) { data = d; next = null; }
}

// Linked List class
class LinkedList
{
Node head; // head of list

/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */
new_node.next = head;

/* 4. Move the head to point to new Node */
head = new_node;
}

/* Returns count of nodes in linked list */
public int getCount()
{
Node temp = head;
int count = 0;
while (temp != null)
{
count++;
temp = temp.next;
}
return count;
}

/* Drier program to test above functions. Ideally
this function should be in a separate user class.
It is kept here to keep code compact */
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
llist.push(1);
llist.push(3);
llist.push(1);
llist.push(2);
llist.push(1);

System.out.println(“Count of nodes is ” +
llist.getCount());
}
}

*****************************************************************************
Method 1 (Using Dummy Nodes)
The strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy.
The dummy node gives tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’, and adding it to tail. When
we are done, the result is in dummy.next.

/* C/C++ program to merge two sorted linked lists */
#include
#include
#include

/* Link list node */
struct Node
{
int data;
struct Node* next;
};

/* pull off the front node of the source and put it in dest */
void MoveNode(struct Node** destRef, struct Node** sourceRef);

/* Takes two lists sorted in increasing order, and splices
their nodes together to make one big sorted list which
is returned. */
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
/* a dummy first node to hang the result on */
struct Node dummy;

/* tail points to the last result node */
struct Node* tail = &dummy;

/* so tail->next is the place to add new nodes
to the result. */
dummy.next = NULL;
while (1)
{
if (a == NULL)
{
/* if either list runs out, use the
other list */
tail->next = b;
break;
}
else if (b == NULL)
{
tail->next = a;
break;
}
if (a->data <= b->data)
MoveNode(&(tail->next), &a);
else
MoveNode(&(tail->next), &b);

tail = tail->next;
}
return(dummy.next);
}

/* UTILITY FUNCTIONS */
/* MoveNode() function takes the node from the front of the
source, and move it to the front of the dest.
It is an error to call this with the source list empty.

Before calling MoveNode():
source == {1, 2, 3}
dest == {1, 2, 3}

Affter calling MoveNode():
source == {2, 3}
dest == {1, 1, 2, 3} */
void MoveNode(struct Node** destRef, struct Node** sourceRef)
{
/* the front source node */
struct Node* newNode = *sourceRef;
assert(newNode != NULL);

/* Advance the source pointer */
*sourceRef = newNode->next;

/* Link the old dest off the new node */
newNode->next = *destRef;

/* Move dest to point to the new node */
*destRef = newNode;
}

/* Function to insert a node at the beginging of the
linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */
(*head_ref) = new_node;
}

/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node!=NULL)
{
printf(“%d “, node->data);
node = node->next;
}
}

/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* res = NULL;
struct Node* a = NULL;
struct Node* b = NULL;

/* Let us create two sorted linked lists to test
the functions
Created lists, a: 5->10->15, b: 2->3->20 */
push(&a, 15);
push(&a, 10);
push(&a, 5);

push(&b, 20);
push(&b, 3);
push(&b, 2);

/* Remove duplicates from linked list */
res = SortedMerge(a, b);

printf(“Merged Linked List is: \n”);
printList(res);

return 0;
}
Run on IDE
Output :

Merged Linked List is:
2 3 5 10 15 20

Method 2 (Using Local References)
This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** “reference” strategy can be used (see Section 1 for details).

struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node* result = NULL;

/* point to the last result pointer */
struct Node** lastPtrRef = &result;

while(1)
{
if (a == NULL)
{
*lastPtrRef = b;
break;
}
else if (b==NULL)
{
*lastPtrRef = a;
break;
}
if(a->data <= b->data)
{
MoveNode(lastPtrRef, &a);
}
else
{
MoveNode(lastPtrRef, &b);
}

/* tricky: advance to point to the next “.next” field */
lastPtrRef = &((*lastPtrRef)->next);
}
return(result);
}
*************************************************************************************************************

MergeSort(headRef)
1) If head is NULL or there is only one element in the Linked List
then return.
2) Else divide the linked list into two halves.
FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
MergeSort(a);
MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here)
and update the head pointer using headRef.
*headRef = SortedMerge(a, b);

// Java program to illustrate merge sorted
// of linkedList

public class linkedList
{
node head = null;
// node a,b;
static class node
{
int val;
node next;

public node(int val)
{
this.val = val;
}
}

node sortedMerge(node a, node b)
{
node result = null;
/* Base cases */
if (a == null)
return b;
if (b == null)
return a;

/* Pick either a or b, and recur */
if (a.val <= b.val) { result = a; result.next = sortedMerge(a.next, b); } else { result = b; result.next = sortedMerge(a, b.next); } return result; } node mergeSort(node h) { // Base case : if head is null if (h == null || h.next == null) { return h; } // get the middle of the list node middle = getMiddle(h); node nextofmiddle = middle.next; // set the next of middle node to null middle.next = null; // Apply mergeSort on left list node left = mergeSort(h); // Apply mergeSort on right list node right = mergeSort(nextofmiddle); // Merge the left and right lists node sortedlist = sortedMerge(left, right); return sortedlist; } // Utility function to get the middle of the linked list node getMiddle(node h) { //Base case if (h == null) return h; node fastptr = h.next; node slowptr = h; // Move fastptr by two and slow ptr by one // Finally slowptr will point to middle node while (fastptr != null) { fastptr = fastptr.next; if(fastptr!=null) { slowptr = slowptr.next; fastptr=fastptr.next; } } return slowptr; } void push(int new_data) { /* allocate node */ node new_node = new node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // Utility function to print the linked list void printList(node headref) { while (headref != null) { System.out.print(headref.val + " "); headref = headref.next; } } public static void main(String[] args) { linkedList li = new linkedList(); /* * Let us create a unsorted linked lists to test the functions Created * lists shall be a: 2->3->20->5->10->15
*/
li.push(15);
li.push(10);
li.push(5);
li.push(20);
li.push(3);
li.push(2);
System.out.println(“Linked List without sorting is :”);
li.printList(li.head);

// Apply merge Sort
li.head = li.mergeSort(li.head);
System.out.print(“\n Sorted Linked List is: \n”);
li.printList(li.head);
}
}

Run on IDE
Time Complexity: O(n Log n)

********************************************************************
1. Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap.

2. What is immutable object? Can you write immutable object?Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String(“Test”);

does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = “Test” Java automatically put that into String pool.

4. What is difference between StringBuffer and StringBuilder in Java ?

Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

5. Write code to find the First non repeated character in the String ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See first non repeated character in the string : Amazon interview question

6. What is the difference between ArrayList and Vector ?
This question is mostly used as a start up question in Technical interviews on the topic of Collection framework . Answer is explained in detail here Difference between ArrayList and Vector .

7. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview question and its open for all, my friend didn’t know the answer so he didn’t mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

8. What is difference between Executor.submit() and Executer.execute() method ?
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task’s return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

9. What is the difference between factory and abstract factory pattern?
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
You can also refer What is Factory method design pattern in Java to know more details.

10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.

11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe.

12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.

13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.

14. What will be the problem if you don’t override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.

15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.

19. What do you understand by thread-safety ? Why is it required ? And finally, how to achieve thread-safety in Java Applications ?

Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.

Let’s first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM – read barriers and write barrier.

A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.
A write barrier flushes out the contents of the processor’s local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.
JMM semantics for synchronized
When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory)
Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.

JMM semantics for Volatile fields
Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

Let’s try to understand the same using the following code

Data data = null;
volatile boolean flag = false;

Thread A
————-
data = new Data();
flag = true; <-- writing to volatile will flush data as well as flag to main memory Thread B ------------- if(flag==true){ <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile="" well="" will="">
use data;