Department of Computer Science and Engineering Page 1
Ques-2: Reverse word in a string Solution class Solution { public String reverseWords(String s) { String[] str = s.trim().split("\\s+"); String out = ""; for (int i = str.length - 1; i > 0; i--) { out += str[i] + " "; } return out + str[0]; } }
Department of Computer Science and Engineering Page 2
Ques-3: Jump Game II Solution class Solution { int ans = 0; public int jump(int[] nums) { int i = 0; while (i < nums.length - 1) { i = helper(i, nums[i], nums); } return ans; } public int helper(int a, int b, int[] nums) { ans++; if (a + b >= nums.length - 1) { return nums.length; } int max = Integer.MIN_VALUE; int temp = 0; for (int i = a; i <= a + b; i++) { if (nums[i] + i >= max) { temp = i; max = nums[i] + i; } } return temp; } }
Department of Computer Science and Engineering Page 3
Ques-4: Move Zeros Solution class Solution { public void moveZeroes(int[] nums) { int left = 0; for (int right = 0; right < nums.length; right++) { if (nums[right] != 0) { int temp = nums[right]; nums[right] = nums[left]; nums[left] = temp; left++; } } } }
Department of Computer Science and Engineering Page 4