Posts

Showing posts from August, 2020

LeetCode - Running Sum of 1d Array Solution - The Coding Shala

Home >> LeetCode >> running sum of 1d array In this post, we will learn how to solve LeetCode's Running Sum of 1d Array problem and its solution in Java. 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]. Running Sum of 1d Array Java Solution Approach 1: Creating a new Array. consider given array is A and we will create a new Array B then:  B[i] = A[0] + A[1] + .... + A[i] or or we can write as B[i] = A[i] + B[i-1]. Time: O(n). Space: O(n). Java Program:  class Solution { public int [] runningSum ( int [] nums ) { int len = nums . length ; int [] ans = new int [ len ]; ans [ 0 ] = nums [ 0 ]; for ( int i = 1 ; i < len ; i ++){ ans [ i ] = ans [ i - 1 ] + nu

LeetCode - Next Greater Element 1 Solution - The Coding Shala

Home >> LeetCode >> next greater element 1 In this post, we will learn how to solve LeetCode's Next Greater Element 1 problem and will implement its solution in Java. Next Greater Element 1 Problem You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are a subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.  The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1. Next Greater Element 1 java

Add Two Numbers in Java - The Coding Shala

Home >> Java Programs >> Add Two Numbers   In this post, we will learn how to add two numbers in Java. Here we will write a Java program to add two numbers using Scanner(user input) and without the scanner. Add Two Number in Java First, we will add two numbers without using a Scanner or without taking any user inputs. Java Program:  public class AddTwoNumbers { public static void main ( String [] args ) { int num1 = 10 ; int num2 = 35 ; int sum ; sum = num1 + num2 ; System . out . println ( "sum of " + num1 + " and " + num2 + " is: " + sum ); } } Output:  sum of 10 and 35 is: 45 Add Two Numbers using Scanner In this Java program will take two user inputs and then print their sum. Java Program:  import java.util.Scanner ; public class AddTwoNumbers { public static void main ( String [] args ) { Scann