Tuesday, 18 June 2019

LRU (Least Recently Used) Cache Implementation in Java


import java.util.HashMap;
import java.util.Map;

class Node{
int key;
int value;
Node pre;
Node next;
public Node(int key , int value) {
this.key = key;
this.value = value;
}
}



class LRUImpl {
Node head , tail;
int CAPACITY, count;
Map<Integer, Node> map ;
public LRUImpl(int capacity) {
this.CAPACITY = capacity;
this.count = 0 ;
this.map = new HashMap<Integer, Node>();
head = new Node(0,0);
tail = new Node(0,0);
head.next = tail;
head.pre = null;
tail.next = null;
tail.pre = head;
}
public void deleteNode(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
public void addNodeToHead(Node node) {
node.next = head.next;
node.pre = head;
head.next.pre = node;
head.next = node;
}
public void printValueFromCache(int key) {
if(map.containsKey(key)) {
Node node = map.get(key);
System.out.println("The value is "+ node.value);
deleteNode(node);
addNodeToHead(node);
}
else {
System.out.println("Invalid Key or Key does not exists");
}
}
public void setValueToCache(int key, int value) {
if(map.containsKey(key)) {
Node node = map.get(key);
deleteNode(node);
addNodeToHead(node);
}
else {
Node node = new Node(key, value);
map.put(key, node);
if(count < this.CAPACITY) {
count++;
addNodeToHead(node);
}
else {
Node nodeRemove = map.get(tail.pre.key);
map.remove(tail.pre.key);
deleteNode(nodeRemove);
addNodeToHead(node);
}
}
}

}

public class LRUCache{
public static void main(String args[]) {
LRUImpl lru = new LRUImpl(3);
lru.setValueToCache(1, 1);
lru.setValueToCache(2, 2);
lru.setValueToCache(3, 3);
lru.printValueFromCache(1);
lru.printValueFromCache(3);
lru.setValueToCache(4, 4);
lru.printValueFromCache(2); // does not exists
}
}

Wednesday, 22 November 2017

LeetCode Java Solution:- Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 1:
Input: [1,3,5,6], 0
Output: 0

Solution:-

class Solution {
    public int searchInsert(int[] nums, int target) {
   
    int start = 0;
    int end = nums.length - 1;
    int mid = 0 ;
    while(start <= end){
    mid = (start + end)  / 2 ;
   
    if(nums[mid] == target){
    return mid;
    }
    else if(nums[mid] < target){
    start = mid + 1;
    }
    else{
    end = mid - 1;
    }
    }
   
    return start;
       
    }
}

Wednesday, 15 November 2017

LeetCode Java Solution:- Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        
        if(nums.length == 0){
            return null;
        }

        return getTreeNode(nums, 0, nums.length -1);
    
        
    }
    
    private TreeNode getTreeNode( int[] nums, int a , int b){
        
        int start = a;
        int end = b ;
        
        if(start > end){
            return null;
        }
        
        int mid = (start +end) / 2 ;
       TreeNode node = new TreeNode(nums[mid]);
        node.left = getTreeNode(nums, start , mid -1);
        
        node.right = getTreeNode(nums, mid+1 , end);
        
        return node;
            
        
        
      
    }

}

LeetCode Java Solution : Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        List<Integer> arr = convertListToArray(head);
        
        return getBInaryTree(arr, 0 , arr.size() -1);
    }
    
    
    
    private List<Integer> convertListToArray(ListNode head){
        List<Integer> arr = new ArrayList<Integer>();
        while(head != null){
            arr.add(head.val);
            head = head.next;
        }
        return arr;
    }
    
    
    private TreeNode getBInaryTree(List<Integer> arr, int start, int end){
        
        if(start > end){
            return null;
        }
        int mid = (start + end) / 2;
            
        TreeNode node = new TreeNode(arr.get(mid));
        node.left = getBInaryTree(arr, start, mid - 1);
        node.right = getBInaryTree(arr, mid + 1 , end);
        
        return node;
        
    }

}

Monday, 13 November 2017

LeetCode - Java Solution Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Solution:-
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        
        int [] ret = new int[m+n];
        int k = 0 , i = 0 , j = 0;
        while( i < m && j < n){
            if(nums1[i] <= nums2[j]){
                ret[k] = nums1[i];
                i++;
            }
            else{
                ret[k] = nums2[j];
                j++;
            }
            k++; 
        }
        if( i == m && j < n){    
            for(int item = j ; item < n ; item++ ){
             ret[k] = nums2[item];
            System.out.println(ret[k] + " "+ nums2[item]);
                k++;   
            }
        }
        
        if( j == n && i < m){
            for(int item = i ; item < m ; item++ ){
                
                ret[k] = nums1[item];
                k++;
            }
        }
        
        for(int l = 0 ; l < ret.length ; l++){
            nums1[l] = ret[l];
        }
    
    }
}

Sunday, 28 May 2017

241. Different Ways to Add Parentheses -- Leet Code- Java -Solution

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]

Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output:
Solution:
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
   
    List<Integer> res = new ArrayList<Integer>();
        
        for(int i = 0 ; i < input.length() ; i++){
        char c = input.charAt(i);
            if(input.charAt(i) == '-' || input.charAt(i) == '+' || input.charAt(i) == '*' ){
                List<Integer> lis1 = diffWaysToCompute(input.substring(0,i));
                List<Integer> lis2 = diffWaysToCompute(input.substring(i + 1));
                
                for(int item1:lis1 ){
                for(int item2:lis2){
                if(c == '-'){
                res.add(item1 - item2);
                }
                else if(c == '+'){
                res.add(item1 + item2);
                }
                else{
                res.add(item1 * item2);
                }
                }
                }
            }
        }
        if(res.size() == 0) {
        res.add(Integer.valueOf(input));
        }
        
        return res;
        
    }
}

Java -Solution- To find Articulation points in a graph

Find Articulation points in a graph so that we can divided the graph into two connected graphs.

Solution:

import java.util.Iterator;
import java.util.LinkedList;

public class Graph {

private int vertices; ;
private LinkedList<Integer> graph[];

private int time;

static final int NIL = -1;
int visited[];

//keep the distance from origin
private int distance[];

//keep the record of lowest distance of subtree
private int lowestAdj[];

//track the parent of vertices
private int parent[];

//articulate points store
private int articulatePoints[];


public Graph(int vertices){
this.vertices = vertices;
graph = new LinkedList[vertices];
visited = new int[vertices];
this.parent = new int[vertices];
this.articulatePoints = new int[vertices];
this.lowestAdj = new int[vertices];
this.distance = new int[vertices];
this.initialize();
}

private void initialize(){
for(int i = 0 ; i < this.vertices ; i++){
graph[i] = new LinkedList<Integer>();
}
}

public void addEdge(int u , int v){
graph[u].add(v);
graph[v].add(u);
}

private void articulateUtil(int u){

int children  = 0 ;

this.visited[u] = 1;

this.distance[u] = this.lowestAdj[u] = ++time;

Iterator<Integer> items = this.graph[u].iterator();

while(items.hasNext()){

int item = items.next();

if(this.visited[item] == 0){
children++;
this.parent[item] = u;
articulateUtil(item);

lowestAdj[u] = Math.min(lowestAdj[u], lowestAdj[item]);

//we need to find two conditions one for parent and another for back edge

if(parent[u] == NIL && children > 1){
this.articulatePoints[u] = 1;
}
else if(this.parent[u] != NIL && this.distance[u] <= this.lowestAdj[item]){
this.articulatePoints[u] = 1;
}

}

else if( item != parent[u] ){
lowestAdj[u] = Math.min(distance[item], lowestAdj[u]);
}
}



}

public void findArticulatePoint(){

for(int i = 0 ; i < this.vertices ; i++){
this.parent[i] = NIL;
}
for(int i = 0 ; i < this.vertices ; i++){
if(this.visited[i] == 0){
this.articulateUtil(i);
}
}
for(int i = 0 ; i < this.vertices ; i++){
if(this.articulatePoints[i] == 1){
System.out.println("This is articulate points " + i);
}
}
}

public static void main(String [] args){
        Graph graph = new Graph(5);
        graph.addEdge(1, 0);
        graph.addEdge(0, 2);
        graph.addEdge(2, 1);
        graph.addEdge(0, 3);
        graph.addEdge(3, 4);
        graph.findArticulatePoint();

}

}

Reference :- http://www.geeksforgeeks.org/articulation-points-or-cut-vertices-in-a-graph/

Sunday, 13 November 2016

Binary Tree Zigzag Level Order Traversal LeetCode Java

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]


Solution:-


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 import java.util.*;
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        HashMap<Integer,LinkedList<Integer>> map = new HashMap<Integer,LinkedList<Integer>> ();
        traverse(root, 1 , map);
        for(int i = 1 ; i <=map.size() ; i++){
            LinkedList<Integer> temp = map.get(i);
         
            if(temp != null){
                List<Integer> item = new ArrayList<Integer>();
                item.addAll(temp);
                res.add(item);
            }
        }
        return res;
     
    }
 
    private void traverse(TreeNode root, int level, HashMap<Integer,LinkedList<Integer>> map){
        if(root != null){
         
            if(map.containsKey(level))
            {
                LinkedList<Integer> temp = map.get(level);
                if(level % 2 == 0){
                    temp.addFirst(root.val);
                }
                else{
                    temp.addLast(root.val);
                }
                map.put(level,temp);
             
            }
            else{
                LinkedList<Integer> link = new LinkedList<Integer>();
                link.add(root.val);
                map.put(level,link);
            }
            level++;
         
            traverse(root.left, level, map);
            traverse(root.right, level, map);
         
        }
     
    }
}

Saturday, 12 November 2016

LeetCode Java : Populating Next Right Pointers in Each Node

Given a binary tree
    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL


Solution:

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
 
    HashMap<Integer,List<TreeLinkNode>> map = new HashMap<Integer,List<TreeLinkNode>>();
    traverse(root, map , 0);
    }
 
    private void traverse(TreeLinkNode root, HashMap<Integer,List<TreeLinkNode>> map , int level){
     
        if(root != null){
         
            if(map.containsKey(level)){
                List<TreeLinkNode> temp = map.get(level);
                TreeLinkNode set = temp.get(temp.size() -1 );
                set.next = root;
                root.next = null;
                temp.add(root);
                map.put(level,temp);
            }
            else{
                root.next = null;
                List<TreeLinkNode> temp = new ArrayList<TreeLinkNode>();
                temp.add(root);
                map.put(level,temp);
            }
            level++;
            traverse(root.left, map , level);
            traverse(root.right, map,level);
         
         
        }
    }
}

Binary Tree Right Side View LeetCode Java

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].



Solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
     
        List<Integer> res = new ArrayList<Integer>();
        HashMap<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();
    traverse(root,map, 0);
 
    for(int i = 0 ; i < map.size() ; i++){
        List<Integer> temp = map.get(i);
        if(temp != null){
            res.add(temp.get(temp.size() -1));
        }
    }
    return res;
     
    }
 
    private void traverse(TreeNode root, HashMap<Integer,List<Integer>> map, int level ){
 
    if(root != null){
     
        if(map.containsKey(level)){
            List<Integer> temp = map.get(level);
            temp.add(root.val);
            map.put(level,temp);
        }
        else{
            List<Integer> temp = new ArrayList<Integer>();
            temp.add(root.val);
            map.put(level,temp);
        }
        level++;
        traverse(root.left,map,level);
        traverse(root.right,map,level);
     
    }
    }
}

Longest Even Length Substring such that Sum of First and Second Half is same

Given a string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits. 
Examples:
Input: str = "123123"
Output: 6
The complete string is of even length and sum of first and second
half digits is same

Input: str = "1538023"
Output: 4
The longest substring with same first and second half sum is "5380"


Solution:

public class Solution{

public static void main(String [] args)
{
String val = "1538023";
int [][] dp = new int[val.length() ][val.length() ];

for(int i = 0 ; i < val.length(); i++){
dp[i][i] = Integer.valueOf(val.charAt(i));
}
int max = 0 ;
for(int c = 2 ; c < val.length() ; c++){
for(int i = 0 ; i < val.length() - c + 1 ; i++){
int j = i + c - 1;
int k = c / 2;
dp[i][j] = dp[i][j-1] + Integer.valueOf(val.charAt(j));
if(c % 2 == 0 && dp[i][j - k] == dp[j-k+1][j] && c > max){
max = c;
}


}
}
System.out.println(max);
}

}