Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 3c5b5f3

Browse files
committedFeb 9, 2022
leet code problems
1 parent 72718c8 commit 3c5b5f3

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed
 

‎src/leetcode/array/Q977.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package leetcode.array;
2+
3+
import java.util.Arrays;
4+
5+
//square of sorted array with two pointer approach
6+
// space o(n)
7+
// time o(n);
8+
//https://leetcode.com/problems/squares-of-a-sorted-array/
9+
public class Q977 {
10+
public static int[] sortedSquares(int[] nums) {
11+
int n = nums.length;
12+
int[] result = new int[nums.length];
13+
int left = 0;
14+
int right = nums.length-1;
15+
for(int i=n-1;i>=0;i--){
16+
int square;
17+
if(Math.abs(nums[left])>Math.abs(nums[right])){
18+
square = nums[left];
19+
left++;
20+
}else{
21+
square = nums[right];
22+
right--;
23+
}
24+
result[i]= square * square;
25+
}
26+
return result;
27+
}
28+
29+
public static void main(String[] args) {
30+
int[] nums = {-7,-3,2,3,11};
31+
int[] result = sortedSquares(nums);
32+
System.out.println(Arrays.toString(result));
33+
}
34+
}

‎src/recursion/NQueenProblem.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package recursion;
2+
3+
import java.util.Arrays;
4+
5+
public class NQueenProblem {
6+
public static void main(String[] args) {
7+
int n=8;
8+
boolean[][] board = new boolean[n][n];
9+
System.out.println(getSolution(board,0));
10+
}
11+
public static int getSolution(boolean[][] board,int row){
12+
if(row== board.length){
13+
display(board);
14+
System.out.println();
15+
return 1;
16+
}
17+
int count=0;
18+
//first place the queen
19+
for (int i=0;i<board[0].length;i++){
20+
21+
if(isSafe(board,row,i)){
22+
board[row][i]=true;
23+
count += getSolution(board,row+1);
24+
board[row][i]=false;
25+
}
26+
27+
}
28+
return count;
29+
}
30+
public static void display(boolean[][] board){
31+
for (boolean[] row:board){
32+
for (boolean col: row){
33+
if(col){
34+
System.out.print("Q ");
35+
}else{
36+
System.out.print("X ");
37+
}
38+
}
39+
System.out.println();
40+
}
41+
}
42+
public static boolean isSafe(boolean[][] board,int row,int col){
43+
//vertical
44+
for(int i=0;i<row;i++){
45+
if(board[i][col]){
46+
return false;
47+
}
48+
}
49+
//left diagonal
50+
int minStep = Math.min(row,col);
51+
for(int i=1;i<minStep;i++){
52+
if(board[row-i][col-i]){
53+
return false;
54+
}
55+
}
56+
//right diagonal
57+
minStep = Math.min(row,board[0].length-1-col);
58+
for(int i=0;i<minStep;i++){
59+
if(board[row-i][col+i]){
60+
return false;
61+
}
62+
}
63+
return true;
64+
}
65+
}

0 commit comments

Comments
 (0)
Please sign in to comment.