Skip to content

Commit 357b29c

Browse files
author
Prashant Jain
committed
Added problem for BitManipulation and DynamicProgramming
1 parent 947c2fc commit 357b29c

2 files changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package in.knowledgegate.dsa.bitmanipulation;
2+
3+
/**
4+
* Given an array nums containing n distinct numbers
5+
* in the range [0, n], return the only number
6+
* in the range that is missing from the array.
7+
*
8+
*
9+
* Example 1:
10+
* Input: nums = [3,0,1]
11+
* Output: 2
12+
* Explanation: n = 3 since there are 3 numbers,
13+
* so all numbers are in the range [0,3]. 2 is the
14+
* missing number in the range since it does not
15+
* appear in nums.
16+
*
17+
* Example 2:
18+
* Input: nums = [0,1]
19+
* Output: 2
20+
* Explanation: n = 2 since there are 2 numbers,
21+
* so all numbers are in the range [0,2]. 2 is the
22+
* missing number in the range since it does not
23+
* appear in nums.
24+
*
25+
* Example 3:
26+
* Input: nums = [9,6,4,2,3,5,7,0,1]
27+
* Output: 8
28+
* Explanation: n = 9 since there are 9 numbers,
29+
* so all numbers are in the range [0,9]. 8 is the
30+
* missing number in the range since it does not
31+
* appear in nums.
32+
*
33+
*
34+
* Constraints:
35+
* n == nums.length
36+
* 1 <= n <= 104
37+
* 0 <= nums[i] <= n
38+
* All the numbers of nums are unique.
39+
*/
40+
public class MissingNumber {
41+
public int missingNumber(int[] nums) {
42+
int num1 = 0, num2 = nums.length;
43+
for (int i = 0; i < nums.length; i++) {
44+
num1 = num1^nums[i];
45+
num2 = num2^i;
46+
}
47+
return num1^num2;
48+
}
49+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package in.knowledgegate.dsa.dynamicprogramming;
2+
3+
/**
4+
* You are climbing a staircase. It takes n steps
5+
* to reach the top.
6+
*
7+
* Each time you can either climb 1 or 2 steps.
8+
* In how many distinct ways can you climb to
9+
* the top?
10+
*
11+
* Example 1:
12+
* Input: n = 2
13+
* Output: 2
14+
* Explanation: There are two ways to climb to the top.
15+
* 1. 1 step + 1 step
16+
* 2. 2 steps
17+
*
18+
* Example 2:
19+
* Input: n = 3
20+
* Output: 3
21+
* Explanation: There are three ways to climb to the top.
22+
* 1. 1 step + 1 step + 1 step
23+
* 2. 1 step + 2 steps
24+
* 3. 2 steps + 1 step
25+
*
26+
*
27+
* Constraints:
28+
* 1 <= n <= 45
29+
*/
30+
public class ClimbingStairs {
31+
/**
32+
* f(n) = f(n-1) + f(n-2)
33+
*/
34+
public int climbStairs(int n) {
35+
if (n == 1) return 1;
36+
if (n == 2) return 2;
37+
38+
int first = 1, second = 2, current = 0;
39+
for (int i = 2; i < n; i++) {
40+
current = first + second;
41+
first = second;
42+
second = current;
43+
}
44+
return current;
45+
}
46+
}

0 commit comments

Comments
 (0)