Detect Cycle in Directed Graph

Given a directed graph, check whether the graph contains a cycle or not. Your function should return complete cycle path if given graph contains at least one cycle, else return null.

Java
Time complexity: O(V+E)
Space complexity: O(V) + O(h), where h is the longest path on call stack

public class DirectCycle<V>{


    public DirectCycle(){
    }

    public List<DirectedEdge<V>> getCycle(Digraph<V> g){
        if (g == null){
            throw new IllegalArgumentException("Invalid param passed!");
        }
        if (g.V() == 0 || g.E() == 0){
            return new ArrayList<>();
        }

        Set<V> whiteSet = new HashSet<>();//initial set of all vertexes
        Set<V> greySet = new HashSet<>();//vertexes processed on current stack
        Set<V> blackSet = new HashSet<>();//already processed vertexes
        Map<V,V> path = new HashMap<>();

        for (V v : g.getVertexes()){
            whiteSet.add(v);
        }

        while (!whiteSet.isEmpty()){
            V v = whiteSet.iterator().next();

            if (dfs(v, g, whiteSet, greySet, blackSet, path)){
                List<DirectedEdge<V>> cycle = buildCycle(v, path);
                return cycle;
            }
        }

        return null;
    }

    private List<DirectedEdge<V>> buildCycle(V v, Map<V, V> path) {
        List<DirectedEdge<V>> cycle = new ArrayList<>();
        V curr = v;
        while (path.containsKey(curr)){
            cycle.add(new DirectedEdge<V>(curr, path.get(curr)));
            V temp = path.get(curr);
            path.remove(curr);
            curr = temp;
        }
        return cycle;
    }

    private boolean dfs(V v, Digraph<V> g, Set<V> whiteSet, Set<V> greySet, Set<V> blackSet, Map<V,V> path){

        move(whiteSet, greySet, v);

        for (DirectedEdge<V> de : g.adj(v)){

            V neighb = de.to();
            path.put(v, neighb);

            if (blackSet.contains(neighb)){
                continue;
            }

            if (greySet.contains(neighb)){
                return true;
            }

            if (dfs(neighb, g, whiteSet, greySet, blackSet, path)){
                return true;
            }
        }

        move(greySet, blackSet, v);
        return false;

    }

    private void move(Set<V> source, Set<V> dest, V v){
        source.remove(v);
        dest.add(v);
    }

}

Advertisements

Leetcode. Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

Java
Time complexity: O(N)
Space complexity: O(1)

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if (gas == null || gas.length == 0){
            return -1;
        }
        
        int start = 0;
        int fuel = 0;
        int tank = 0;
        
        for (int i = 0; i < gas.length; ++i){
            fuel += gas[i] - cost[i];
            tank += gas[i] - cost[i];
            if (tank < 0){ 
                tank = 0; start = i + 1; 
            } 
        } 
        return fuel >= 0 ? start : -1;
        
    }
}

Go
Time complexity: O(N)
Space complexity: O(1)

func canCompleteCircuit(gas []int, cost []int) int {
    if gas == nil || len(gas) == 0{
        return -1;
    }
    var fuel, tank, start int = 0, 0, 0
    
    for i := 0; i < len(gas); i++ {
        fuel += gas[i] - cost[i]
        tank += gas[i] - cost[i]
        if tank < 0{
            tank = 0
            start = i + 1
        }
    }
    
    if fuel < 0{
        return -1
    } else{
        return start;
    }
}

Leetcode. Find All Duplicates in an Array

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]


Java
Time complexity: O(N)
Space complexity: O(1)

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        if (nums == null || nums.length == 0){
            return new ArrayList<Integer>();
        }
        List<Integer> res = new ArrayList<Integer>();
        
        for (int n : nums){
            int idx = Math.abs(n);
            if (nums[idx-1] < 0){
                res.add(idx);
            }
            nums[idx-1] = ~nums[idx-1] + 1;
        }
        //restore array
        for (int i = 0; i < nums.length; ++i){
            nums[i] = Math.abs(nums[i]);
        }
        return res;
    }
}

Digraph With Adjacency List

Inspired by Digraph (Algorithms 4/e) – Algorithms, 4th Edition

Digraph.java

//Digraph implementation with adjacency list
public class Digraph<V>{

    private Map<V,List<DirectedEdge<V>>> vertexes;

    private int eCount;

    public Digraph(){
        this.vertexes = new HashMap<>();
    }

    public int V(){
        return vertexes.size();
    }

    public int E(){
        return eCount;
    }

    public List<DirectedEdge<V>> adj(V vertex){
        return vertexes.get(vertex);
    }

    public void addEdge(DirectedEdge<V> de){
        if (de == null){
            return;
        }
        if (!vertexes.containsKey(de.from())){
            vertexes.put(de.from(), new ArrayList<>());
        }
        if (!vertexes.containsKey(de.to())){
            vertexes.put(de.to(), new ArrayList<>());
        }
        vertexes.get(de.from()).add(de);
        ++eCount;
    }

    //O(V+E)
    public List<DirectedEdge<V>> getEdges(){
        List<DirectedEdge<V>> res = new ArrayList<DirectedEdge<V>>(eCount);
        for (V v : vertexes.keySet()){
            res.addAll(vertexes.get(v));
        }
        return res;
    }

    public Set<V> getVertexes(){
        return vertexes.keySet();
    }
}

DirectedEdge.java

public class DirectedEdge<V>{

    private V from;
    private V to;

    public DirectedEdge(V from, V to){
        this.from = from;
        this.to = to;
    }

    public V from(){
        return from;
    }

    public V to(){
        return to;
    }

    @Override
    public String toString(){
        return from.toString() + "-->" + to.toString();
    }

}

Lintcode. Best Time to Buy and Sell Stock I, II, III

Best Time to Buy and Sell Stock I

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example
Given array [3,2,3,1,2], return 1.

Python
Time complexity: O(N)
Space complexity: O(1)

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        if (not prices or len(prices) <= 1):
            return 0
            
        minSoFar = prices[0]
        profit = 0
        
        for v in prices[1:]:
            minSoFar = min(minSoFar, v)
            profit = max(profit, v - minSoFar)

        return profit

 

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example
Given an example [2,1,2,0,1], return 2.

Java
Time complexity: O(N)
Space complexity: O(1)

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     * As a solution one can find sum of contiguous delta trades, where 
     * 'delta trade' stands for buy-sell compound transaction.
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length <= 0){
            return 0;
        }
        
        int profit = 0;
        
        for (int i = 1; i < prices.length; ++i){
            profit += Math.max(0, prices[i] - prices[i-1]);
        }
        
        return profit;
    }
}

 

Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Notice : You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example

Given an example [4,4,6,1,1,4,2,5], return 6.

Java
Time complexity: O(N)
Space complexity: O(1)

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length == 0){
            return 0;
        }
        
        int buyFirst = Integer.MIN_VALUE;
        int sellFirst = 0;
        int buySecond = Integer.MIN_VALUE;
        int sellSecond = 0;
        
        for (int i = 0; i < prices.length; ++i){
            buyFirst = Math.max(buyFirst, -prices[i]);
            sellFirst = Math.max(buyFirst + prices[i], sellFirst);
            buySecond = Math.max(buySecond, sellFirst - prices[i]);
            sellSecond = Math.max(sellSecond, buySecond + prices[i]);
        }
        
        return sellSecond;
    }
}

Check If Graph is Bipartite

A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, or u belongs to V and v to U. We can also say that there is no edge that connects vertices of same set.
A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color.

Below code implements this algorithm.

Java
Time complexity: O(V+E)
Space complexity: O(V)

public class BipartiteGraphValidator {

    public static <V> boolean isBipartite(Graph<V> g){
        if (g == null || g.V() <= 1){
            return false;
        }

        Map<V, Boolean> coloredPath = new HashMap<>();//strongly connected graphs only
        Queue<V> q = new LinkedList<V>();

        V source = g.getVertexes().iterator().next();
        q.offer(source);
        coloredPath.put(source, Boolean.TRUE);

        while (q.size() > 0){
            V curr = q.poll();
            for (V neighb : g.adj(curr)){
                if (coloredPath.containsKey(neighb) && color(curr, coloredPath) == color(neighb, coloredPath)){
                    return false;
                }

                if (!coloredPath.containsKey(neighb)){
                    q.offer(neighb);
                }
                coloredPath.put(neighb, !color(curr, coloredPath));
            }
        }

        return true;
    }

    private static <V> boolean color(V v, Map<V, Boolean> coloredPath){
        return coloredPath.get(v);
    }
}

Trie

Trie, or prefix tree, is a search tree that stores associative arrays or dynamically resizable collections per node. From every regular node one can search a value by key (key defines position of node with corresponding value in collection). Nodes on every path starting from level 0 (direct children of root) share the common prefix. Path from level 0 to terminal node represents a complete word (for example, ‘MAP’).

One can search a word in trie in O(M) time, where M is length of word to be searched. In case of word miss, search will terminate on some node along the path and return faster than in O(M) (depends on concrete structure of trie). Insertions and deletions will perform at worst in O(M).
trie2
Java

Time complexity: O(M) for search, insert and delete, M – length of word

Space complexity: O(N*26) -> O(N), per every node we store constant number of references to child nodes, bounded by size of alphabet


class TrieNode {

        public static final int R = 26;//size of alphabet

        private TrieNode[] next = new TrieNode[R];

        private boolean isTerminal;

        // Initialize your data structure here.
        public TrieNode() {

        }
        public void setTerminal(){
            this.isTerminal = true;
        }

        public boolean isTerminal(){
            return isTerminal;
        }

        public TrieNode setNext(int c){
            int k = c - 'a';
            if (next[k] != null){
                return next[k];
            } else {
                TrieNode newNode = new TrieNode();
                next[k] = newNode;
                return newNode;
            }
        }

        public TrieNode getNext(char c){            
            return next[c - 'a'];
        }
}

public class Trie {
        private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode curr = root;
        for (Character c : word.toCharArray()){
            curr = curr.setNext(c);
        }
        curr.setTerminal();
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode curr = root;
        for (Character c : word.toCharArray()){
            curr = curr.getNext(c);
            if (curr == null){
                return false;
            }
        }
        return curr.isTerminal();
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode curr = root;
        for (Character c : prefix.toCharArray()){
            curr = curr.getNext(c);
            if (curr == null){
                return false;
            }
        }
        return true;
    }
}