Posts

Shuffle the Array

Program Description: Shuffle the Array Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7]  Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. Example 2: Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] Example 3: Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2] Constraints: 1 <= n <= 500 nums.length == 2n 1 <= nums[i] <= 10^3 Solution : class Solution {     public int[] shuffle(int[] nums, int n) {         int InsertValue = nums[n];         for(int i=1; i< nums.length; i+=2){             if(n>nums.length-1){                 break;             }             InsertValue = nums[n]; ...

Running Sum of 1D Array

Program Description: Running Sum of 1D Array Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. Example 2: Input: nums = [1,1,1,1,1] Output: [1,2,3,4,5] Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. Example 3: Input: nums = [3,1,2,10,1] Output: [3,4,6,16,17]   Constraints: 1 <= nums.length <= 1000 -10^6 <= nums[i] <= 10^6 Solution: class Solution {     public int[] runningSum(int[] nums) {         int sm = 0;         int[] runningSum = new int[nums.length];         for(int i=0; i < nums.length; i++){             sm += nums[i];             runningSum[i] = sm;         }   ...

Two Sum

Two Sum: Program Description: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1]   Constraints: 2 <= nums.length <= 105 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. : Solution : class Solution {     public int[] twoSum(int[] nums, int tar) {         Map<Integer, Integer> dic = new HashMap<Integer, Integer>();                  for(int i=0; i<nums.length ; i++){           ...