Queue Removals

	public static class Pair {
		int index;
		int value;

		public Pair(int index, int value) {
			super();
			this.index = index;
			this.value = value;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public int getValue() {
			return value;
		}

		public void setValue(int value) {
			this.value = value;
		}

	}

	public static int[] findPositions(int[] arr, int x) {
		Queue<Pair> q = new LinkedList<Pair>();
		for (int i = 0; i < arr.length; i++)
			q.add(new Pair(i + 1, arr[i]));
		ArrayList<Integer> removed = new ArrayList<Integer>();
		for (int i = x; i >= 1; i--) {
			int pops = x;
			PriorityQueue<Pair> maxHeap = new PriorityQueue<Pair>(new Comparator<Pair>() {
				@Override
				public int compare(Pair o1, Pair o2) {
					if (o1.getValue() == o2.getValue())
						return Integer.compare(o1.getIndex(), o2.getIndex());
					return -Integer.compare(o1.getValue(), o2.getValue());
				}
			});
			Queue<Pair> temp = new LinkedList<Pair>();
			while (pops != 0 && !q.isEmpty()) {
				Pair c = q.poll();
				maxHeap.add(c);
				temp.add(c);
				pops--;
			}
			Pair ToRemove = maxHeap.remove();
			int ToRemoveIndex = ToRemove.getIndex();
			removed.add(ToRemoveIndex);
			while (!temp.isEmpty()) {
				Pair a = temp.poll();
				if (a.getIndex() != ToRemoveIndex) {
					q.add((a.getValue() > 0) ? new Pair(a.getIndex(), a.getValue() - 1) : a);
				}
			}
		}
		int[] out = new int[removed.size()];
		for (int i = 0; i < out.length; i++)
			out[i] = removed.get(i);
		return out;
	}

Caesar Cipher

Caesar Cipher

 public static String caesarCipher(String input, int rotationFactor) {
    // Write your code here
StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z') {
                char newChar = (char) (input.charAt(i) + rotationFactor%26);
                sb.append((newChar >= 'a' && newChar <= 'z') ? newChar : (char) (newChar - 'z' - 1 + 'a'));
            } else if (input.charAt(i) >= 'A' && input.charAt(i) <= 'Z') {
                char newChar = (char) (input.charAt(i) + rotationFactor%26);
                sb.append((newChar >= 'A' && newChar <= 'Z') ? newChar : (char) (newChar - 'Z' - 1 + 'A'));
            } else
                sb.append(input.charAt(i));
        }
        return sb.toString();
    }

1460. Make Two Arrays Equal by Reversing Sub-arrays

1460. Make Two Arrays Equal by Reversing Sub-arrays

class Solution {
    public boolean canBeEqual(int[] target, int[] arr) {
        HashMap<Integer,Integer> h = new HashMap<>();
        for (int a: arr){
            h.put(a ,h.getOrDefault(a,0)+1);
        }
        for(int b: target){
            if(h.get(b)!= null)
            h.put(b,h.getOrDefault(b,0)-1);
            else return false;
        }
        for(int c: h.keySet()){
            if(h.get(c) != 0) return false;
        }
        return true;
    }
}

118. Pascal’s Triangle

118. Pascal’s Triangle

class Solution {
      public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> all = new ArrayList();
        
      List<Integer> first = new ArrayList<>();
      first.add(1);
      all.add(first);
      
      if(numRows >=2) {
    	  List<Integer> second = new ArrayList<>();
          second.add(1);
          second.add(1);
          all.add(second);  
      }
      for(int i = 2;i < numRows; i++) {
    	  List<Integer> row = new ArrayList<>();
    	  row.add(1);
    	  int start =0;
    	  for(int j = 1; start<all.get(i-1).size()-1; j++) {
    		  int a = all.get(i-1).get(start)+all.get(i-1).get(start+1);
    		  start++;
    		  row.add(a);
    	  }
    	  
    	 row.add(1);
    	 all.add(row); 
      }
        
        return all;
    }
}

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int len = 0;
        ListNode current = head;
        while(current != null){
            len++;
            current = current.next;
        }
       int required = len - n;
        if(required == 0) return head.next;
        ListNode c = head;
        for(int i =0; i < len; i++){
            if(i == required-1) {
                c.next = c.next.next;
               
            }
             else c = c.next;
        }
        return head;
    }
}

125. Valid Palindrome

125. Valid Palindrome

class Solution {
    public boolean isPalindrome(String s) {

        StringBuilder sIgnoreBuffer = new StringBuilder();
        for (int i = 0; i < s.length(); i++){
            if((s.charAt(i)>='0' && s.charAt(i)<='9')||(s.charAt(i) >= 'a' && s.charAt(i) <= 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z'))
                sIgnoreBuffer.append(Character.toLowerCase(s.charAt(i)));
        }
    
        String sIgnore = sIgnoreBuffer.toString();
        int start = 0;
        int end = sIgnore.length() - 1;   
                                
        while(start < end){
            if(sIgnore.charAt(start) == sIgnore.charAt(end)){
                start++;
                end --;
            } else return false;
        }
       return true;
}}

48. Rotate Image

48. Rotate Image

class Solution {
    public void rotate(int[][] matrix) {
 
        for(int i = 0; i < matrix.length; i++){
            for (int j = i; j < matrix.length; j++){
                swap(i,j,j,i,matrix);

            }
        }
        
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix.length/2; j++){
            swap(i,j,i,matrix.length-1-j,matrix);

                }
        }
        
        
    }
    public void swap(int i, int j, int x, int y, int [][] matrix){
        int temp = matrix[i][j];
        matrix[i][j] = matrix[x][y];
        matrix[x][y] = temp;
    }
}

}

36. Valid Sudoku

36. Valid Sudoku

   class Solution {
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < board.length; i++) { HashSet dataInRow = new HashSet();
for (int j = 0; j < board.length; j++) {
if (board[i][j] != '.')
if (dataInRow.contains(board[i][j]))
return false;
else
dataInRow.add(board[i][j]);
}
} for (int j = 0; j < board.length; j++) {
        HashSet<Character> dataInRow = new HashSet<Character>();
        for (int i = 0; i < board.length; i++) {
            if (board[i][j] != '.')
                if (dataInRow.contains(board[i][j]))
                    return false;
                else
                    dataInRow.add(board[i][j]);
        }
    }
    for (int i = 0; i < board.length; i = i + 3) {
        for (int j = 0; j < board.length; j = j + 3) {
            if (!checkValid(i, j, board))
                return false;
        }
    }

    return true;
}

private boolean checkValid(int a, int b, char[][] board) {
    HashSet<Character> dataInSquare = new HashSet<Character>();
    int aEnd = a + 3;
    int bEnd = b + 3;
    for (int i = a; i < aEnd; i++) {
        for (int j = b; j < bEnd; j++) {
            if (board[i][j] != '.')
                if (dataInSquare.contains(board[i][j]))
                    return false;
                else
                    dataInSquare.add(board[i][j]);
        }
    }
    return true;
}

}

Mark and Toys

Mark and Toys
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the maximumToys function below.
    static int maximumToys(int[] prices, int k) {
        Arrays.sort(prices);
        int max = 0;
        int total = 0;
        for (int i = 0; i < prices.length; i++) {
            total += prices[i];
            if (total < k)
                max++;
            else
                return max;

        }
        return max;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nk = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nk[0]);

        int k = Integer.parseInt(nk[1]);

        int[] prices = new int[n];

        String[] pricesItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int pricesItem = Integer.parseInt(pricesItems[i]);
            prices[i] = pricesItem;
        }

        int result = maximumToys(prices, k);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

Find the Running Median

Find the Running Median

import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

    /*
     * Complete the runningMedian function below.
     */
    static double[] runningMedian(int[] a) {
        /*
         * Write your code here.
         */

        
        double[] out = new double[a.length];
        PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return -Integer.compare(o1, o2);
            }
        });
        double median = 0;
        if(a.length == 1) {
            out[0] = a[0];
            return out;
        }
        for (int i = 0; i < a.length; i++) {
            if( i == 0) {
                out[0] = a[0];
            } else if (i == 1) {
                minHeap.add(Integer.max(a[0], a[1]));
                maxHeap.add(Integer.min(a[0], a[1]));
                out[i] = ((double) a[i - 1] + (double) a[i]) / 2;
                median = out[i];
            } else {
                       
                if(a[i] > median) {
                   minHeap.add(a[i]);
               } else if(a[i]<= median) {
                   maxHeap.add(a[i]);
               }
                
                if(Math.abs(minHeap.size() - maxHeap.size())>1) {
                    if(minHeap.size() > maxHeap.size())
                        maxHeap.add(minHeap.remove());
                    else minHeap.add(maxHeap.remove());
                }
                
                
                if(minHeap.size() == maxHeap.size())
                out[i] = ((double)minHeap.peek() + (double) maxHeap.peek())/2;
                else if (minHeap.size() > maxHeap.size())
                    out[i] = minHeap.peek().doubleValue();
                else if (maxHeap.size() > minHeap.size())
                    out[i] = maxHeap.peek().doubleValue();
                median = out[i];
                
            }
        }
        return out;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int aCount = Integer.parseInt(scanner.nextLine().trim());

        int[] a = new int[aCount];

        for (int aItr = 0; aItr < aCount; aItr++) {
            int aItem = Integer.parseInt(scanner.nextLine().trim());
            a[aItr] = aItem;
        }

        double[] result = runningMedian(a);

        for (int resultItr = 0; resultItr < result.length; resultItr++) {
            bufferedWriter.write(String.valueOf(result[resultItr]));

            if (resultItr != result.length - 1) {
                bufferedWriter.write("\n");
            }
        }

        bufferedWriter.newLine();

        bufferedWriter.close();
    }
}