Also if two elements appear for same number of times, one which appeared first in the input array should be placed first.

For example, if A =

`[7, 6, 1, 7, 1, 3, 6, 6, 2]`

The output should be

`[6, 6, 6, 7, 7, 1, 1, 3, 2]`

Solution: First calculate the frequency for the given elements.

`Value -> Frequency`

6 -> 3

7 -> 2

1 -> 2

3 -> 1

2 -> 1

Then store the elements in a priority queue (max-heap) based on the frequency of values. Then delete the elements from priority queue one by one and add them to resultant array. Here is the Java implementation.

import java.util.*; public class SortByFrequency { public static void main(String []args) { int []arr = {5, 1, 5, 1, 1, 7, 8, 4, 8, 2}; int []freqSorted = sortByFrequency(arr); Arrays.stream(freqSorted).forEach(System.out::println); } private static int[] sortByFrequency(int []arr) { //calculate frequencies of elements Map<Integer, Integer> freqMap = getFrequencyMap(arr); //Comparator for storing value, frequency tuples in priority queue (max heap) //Using the Java 8 Lambdas to define comparator Comparator< Map.Entry<Integer,Integer> > descFreqComparator = (e1, e2) -> e2.getValue() - e1.getValue(); PriorityQueue< Map.Entry<Integer, Integer> > pq = new PriorityQueue<>(descFreqComparator); //Add map entries to max heap for(Map.Entry<Integer, Integer> entry: freqMap.entrySet()) { pq.add(entry); } //Form the result array by deleting elements from priority queue int []result = new int[arr.length]; int i = 0; while( !pq.isEmpty() ) { Map.Entry<Integer, Integer> entry = pq.poll(); for(int j = 0; j < entry.getValue(); j++) { result[i++] = entry.getKey(); } } return result; } private static Map<Integer, Integer> getFrequencyMap(int []arr) { //LinkedHashMap to preserve the original order of elements in arr Map<Integer, Integer> freqMap = new LinkedHashMap<>(); int i; for(i = 0; i < arr.length; i++) { if(freqMap.containsKey(arr[i])) { freqMap.put(arr[i], freqMap.get(arr[i])+1); } else { freqMap.put(arr[i], 1); } } return freqMap; } }

Time Complexity: `O(n log n)`

because we are using max heap to store the element, frequency pairs for retrieving them in descending order of their frequencies.

Space Complexity: `O(n)`

Extra storage for frequency map and resultant array.

`Comparator`

interface, and the other is through `Comparable`

interface. Let us see the similarities and differences between them and when should we use them.
If we are defining a class, and we want a natural ordering of a collection of the objects of the class when sorted, then we implement `Comparable`

interface. For example if we are defining a Book class as part of a library project, and we want to sort the collection of books by the title, then we can define the class like the following.

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Comparators { public static void main(String []args) { List<Book> books = new ArrayList<>(); books.add(new Book("The C Programming Language", "Dennis Ritche", 1978)); books.add(new Book("The Art of Computer Programming", "Donald Knuth", 1962)); books.add(new Book("Introduction to Algorithms", "CLR", 1990)); Collections.sort(books); books.forEach(System.out::println); //Java 8 way of printing } } class Book implements Comparable<Book>{ private String title; private String author; private int releaseYear; public Book(String title, String author, int releaseYear) { this.title = title; this.author = author; this.releaseYear = releaseYear; } @Override public int compareTo(Book o) { return this.title.compareTo(o.title); //Utilize String compareTo method } public String toString() { return "[" + title + ", " + author + ", " + releaseYear + "]"; } }

Suppose at some later point we also wanted sort the books based on the year published. We can create a `BookYearComparator`

class which implements the `Comparator`

interface and sort them in that like the following.

class BookYearComparator implements Comparator<Book> { @Override public int compare(Book o1, Book o2) { return o1.getReleaseYear()-o2.getReleaseYear(); } }

Collections.sort(books, new BookYearComparator()); books.forEach(System.out::println);

With Lambda expressions from Java 8, custom comparators are simple to code. The `BookYearComparator`

can be defined as lambda expression like the following. No need of creating a separate class just for defining the ordering. This way the lambdas have more expressive power than just classes and interfaces.

Collections.sort(books, Comparator.comparingInt(Book::getReleaseYear));

Similarly for sorting the books by author, you can use the following expression.

Collections.sort(books, Comparator.comparing(Book::getAuthor));

Alternate syntax for specifying comparator as Lambda expression is as follows.

Collections.sort(books, (b1, b2)->b1.getReleaseYear()-b2.getReleaseYear()); books.forEach(System.out::println); Collections.sort(books, (b1, b2)->b1.getAuthor().compareTo(b2.getAuthor())); books.forEach(System.out::println);

The above syntax is useful when we have to use more than one field in the comparison. For example we want to sort the books first by title, then by the release year. We can sort them like the following. The lambda expression compares the release years only of the titles are equal, other wise it sorts according to the title.

Collections.sort(books, (b1, b2)->{ if(b1.getTitle().equals(b2.getTitle())) return b1.getReleaseYear()-b2.getReleaseYear(); return b1.getTitle().compareTo(b2.getTitle()); });]]>

comparison between two variables of different types results in a compile error.

But in Python this will simply evaluate to false. So beware when comparing a string and int

containg same values. when we print, they look the same.

I actually faced this issue when I am receving a param from a config file

and comparing with some int value in the program something similar to the following.

]]>

For example let us consider two strings “java”, “lava” they both differ by just one character. we can change the first character in either of them to make them equal.

Similarly, the words “at”, “bat” also have an edit distance of 1 because either we can add “b” to the first string, or delete “b” from the second string to make them euqal.

By looking at the problem statement, one can think of a dynamic programming solution which takes O(n^2) time. However, it would an over kill to solve this problem.

Let’s observe some thing. Two strings can not have an edit distance of 1 if their lengths differ by more than 1 characters.

So we can simplify our approach to work on the two use cases.

which are either of equal length, or

one string longer than the other by just one character.

Lets see some representative test cases we need to handle.

(“abc”, “bc”), (“abc”, “ab”), (“string”, “sxring”), (“algorithm”, “algoritm”) etc.

If the two strings are equal, we just count the number of mismatches at each index in the two strings.

Otherwise, we check if the shorter string is a sub-sequence of the longer string except one character. In this case we calculate the number matching characters which should be equal to the length of the shorter string.

Here is the Java implementation of the above approach. The time complexity would be linear O(n).

]]>

For example consider the array

`A = [1, 1, 0, 1, 0, 0, 1], K = 2,`

the maximum length is `A[0:4]`

This problem can be solved using

`front`

and `back`

which defines a window. We keep expanding the window by incrementing the `back`

index as long as the window contains less than or equal to K zeros. That means, at any time, the window contains at most K 0’s. If it exceeds K, we increment the `front`

index to reduce the number of zeros to K. Continue this procedure until the `back`

index reaches the end of the array. We also keep track of the largest window during this process.This algorithm takes O(n) time.

Here is the C++ code.

Problem Source: SPOJ REPROAD ]]>

Select any index i such that

`1 <= i <= N`

, Mark `A[i] = 0`

, move left by filling each element one greater than it’s rightSimilarly move right, and fill each element which is one greater than it’s left.

For example consider an array of length 5, and we choose the index 3, the array would be

`A = [2, 1, 0, 1, 2]`

If we perform several iterations by choosing different indexes each time,

we have to output the maximum number, each element can get during all the iterations.

Consider that we repeat the procedure for the above array with Index 2

`A = [1, 0, 1, 2, 3]`

So after two iterations at indexes 2, and 3, maximum elements would be

`MAX_A = [2, 1, 1, 2, 3]`

To find

`MAX_A`

, at first, it looks like we need to repeat the procedure m times for m indexes,which leads to

`O(m*n)`

complexity solution.What will be the maximum number an element can get?

How? Lets consider the same array as above, choose index 1, the array would be

`A = [0, 1, 2, 3, 4]`

Choose index 5, the array would be

`A = [4, 3, 2, 1, 0]`

So it is enough to perform the iteration with the left most and right most indexes,

the maximum element at each index i would be

`max( abs(i-left), abs(i-right))`

So the time complexity will be

`O(n)`

.Here is the C++ code for the same.

Problem Source: The Army – Codechef ]]>

If the root is labelled

`i`

, it’s left child is labelled `2*i`

and right child is labelled as `2*i+1`

.`1`

/ \

2 3

/ \ / \

4 5 6 7

Given two nodes from this tree, how do we find the length of the path between them?

For example the path length between 2 and 3 is 2 (2->1->3)

Similarly path length between 4 and 1 is 2, and between 4 and 7 it is 4 (4->2->1->3->7)

In a binary tree, two nodes can be connected in two possible ways.

- Either one of the nodes can be ancestor of the other, or
- Both of them are connected by some common ancestor.

For example, take 1 and 5, 1 is an ancestor of 5.

Take 4 and 5, they are connected by their lowest common ancestor 2, so the path goes has to via 2.

So this problem can be solved by finding the Lowest Common Ancestor (LCA) of the two nodes and adding the distances between the nodes to their LCA.

We use the bottom up approach here. Start from the given two nodes and try to search for lowest common ancestor by going up since we can easily go the parent node by dividing the node by 2. While finding the LCA, we can also calculate the path length.

Since we traverse through the tree for at most the height of the tree, the time complexity will be O(log n).

Here is the C++ code.

Problem source: Codechef

A garments shop has “Buy 2, Get 2” offer for it’s customers. Whatever the items may be, they charge for costliest items from an order and give the cheapest ones free.

However we can divide the items into multiple orders to save more.

For example, Let us say we have 6 items with prices

`200, 600, 100, 900, 800, 700`

. If we take them as one order, we will have to pay 3000.6 items are divided into two groups

`{900,800,200,100}, {700,600}`

because they charge for highest price items. So the total bill would be` 900+800+700+600 = 3000`

Suppose we divide the items into two groups

`{900,800,700,600}, {200,100}`

we need to pay only `900+800+200+100 = 2000`

Now the problem is, given a list of prices, how do we calculate the minimum amount we need to pay?

This is a simple greedy algorithm. We just need to sort all the prices in descending order and group them into 4 per order. The last order might contain less than 4 items.

Here is the C++ code for the same

]]>

What is the minumum number of jumps he has to make to reach the top?

A simple math problem which can be solved using a simple greedy approach. Try to make as many maximum jumps as possible before reaching the top. Take a smaller jump if needed at the end.

For example if there are 10 steps, he can make two maximum jumps of 5 steps each to reach the top.

If there 8 steps, First he can jump 5 steps and then jump 3 steps. So within 2 jumps, he can reach the top.

The code for this very simple. This problem can also be generalized by customizing the jump capacity to any number instead of a fixed number 5.

`#include <iostream>`

#include <cstdio>

using namespace std;

`int main()`

{

int loc;

scanf("%d", &loc);

printf("%d\n",loc/5 + (loc%5 == 0?0:1));

return 0;

}

]]>`Sum(A[i]...A[j])`

,For example, let the array be

`[15, 6, 1, 12, 7, 4, 10]`

`Sum(A[1:3]) = 15+6+1 = 22`

Sum(A[4:6]) = 12+7+4 = 23

...

The simplest solution is to iterate through the elements from i to j and return the sum.

However this will be good enough if we have a small number of queries. What if we need to run many queries?

In worst case this is takes O(n

How can we reduce the time complexity?

If we pre-process the array by calculating the prefix array, we can answer each query in O(1) time.

For the above example calculate the prefix array by using the formula

`Prefix[i] = Prefix[i-1]+A[i]`

`Prefix = [15, 21, 22, 34, 41, 45, 55]`

Now the partial sums can be calculated as follows

`Sum(A[i:j]) = Prefix[j] - Prefix[i-1] if i > 1`

= Prefix[j] if i=1

Here is the Java function which implements the above

`long partialSum(int []prefixArr, int start, int end) {`

long sum = arr[end];

if( start > 0)

sum -= arr[start-1];

return sum;

}

]]>