Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions frequently asked coding ques
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
//leetcode 875
class Solution {

public int minEatingSpeed(int[] piles, int h) {
// Initalize the left and right boundaries
int left = 1, right = 1;
for (int pile : piles) {
right = Math.max(right, pile);
}

while (left < right) {
// Get the middle index between left and right boundary indexes.
// hourSpent stands for the total hour Koko spends.
int middle = (left + right) / 2;
int hourSpent = 0;

// Iterate over the piles and calculate hourSpent.
// We increase the hourSpent by ceil(pile / middle)
for (int pile : piles) {
hourSpent += Math.ceil((double) pile / middle);
}

// Check if middle is a workable speed, and cut the search space by half.
if (hourSpent <= h) {
right = middle;
} else {
left = middle + 1;
}
}

// Once the left and right boundaries coincide, we find the target value,
// that is, the minimum workable eating speed.
return right;
}
}

//sort 0s,1, and 2s array
class Solution {
// Function to sort an array of 0s, 1s, and 2s
public void sort012(int[] arr) {
// code here

int low =0;
int mid =0;
int high = arr.length-1;

while(mid <= high){
if(arr[mid] == 0){
swap(arr,low,mid);
low++;
mid++;
}
else if(arr[mid] == 1){
mid++;
}else {
swap(arr,mid,high);
high--;
}
}
}

private void swap(int[] arr, int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

//leetcode 37
class Solution {
public void solveSudoku(char[][] board) {
if (board == null || board.length == 0) return;
solve(board);
}

private boolean solve(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (solve(board)) return true;
else board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}

private boolean isValid(char[][] board, int row, int col, char c) {
int nRow = 3 * (row / 3);
int nCol = 3 * (col / 3);
for (int i = 0; i < 9; i++) {
if (board[i][col] == c) return false;
if (board[row][i] == c) return false;
if (board[nRow + i / 3][nCol + i % 3] == c) return false;
}
return true;
}
}

//leetcode 128
class Solution {
public int longestConsecutive(int[] nums) {
Arrays.sort(nums);
int count = 0;
int temp = 1;
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return 1;
}
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == (nums[i + 1] - 1)) {
temp++;
count = Math.max(count, temp);
} else if (nums[i] == (nums[i + 1])) {
count = Math.max(count, temp);
} else {
temp = 1;
count = Math.max(count, temp);
}
}
return count;
}
}