Skip to content

Commit 44b7c88

Browse files
committed
Adding Simple Solution for Problem - 1299 - Replace Elements on Right Side
1 parent d04b703 commit 44b7c88

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 1299
6+
## Problem Name: Replace Elements with Greatest Element on Right Side
7+
##===================================
8+
#
9+
#Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
10+
#
11+
#After doing so, return the array.
12+
#
13+
#Example 1:
14+
#
15+
#Input: arr = [17,18,5,4,6,1]
16+
#Output: [18,6,6,6,1,-1]
17+
class Solution:
18+
def replaceElements(self, array):
19+
tmpArray = [-1 for _ in range(len(array))] #Creating tmpArray and fill it up with -1 for len(array)
20+
for i in range(len(array)) - 2, -1, -1): #Loop through array in reverse manner.
21+
tmpArray[i] = max(tmpArray[i + 1], array[i + 1]) #Update the tmpArray[i] by using max function between actual and tmpArray.
22+
return tmpArray #Returning tmpArray at the end.
23+
24+
#Example
25+
#array = [17, 18, 5, 4, 6, 1]
26+
#tmpArray = [-1, -1, -1, -1, -1, -1]
27+
#Now range will be range(4, -1, -1)
28+
#array = [17, 18, 5, 4, 6, 1]
29+
#tmpArray = [-1, -1, -1, -1, -1, -1]
30+
#Index = [0, 1, 2, 3, 4, 5]
31+
#i = 4
32+
#tmpArray[4] = max(tmpArray[5], array[5]) = max(-1, 1) = 1
33+
#tmpArray = [-1, -1, -1, -1, 1, -1]
34+
#array = [17, 18, 5, 4, 6, 1]
35+
#i = 3
36+
#tmpArray[3] =max(tmpArray[4], array[4]) = max(1, 6) = 6
37+
#tmpArray = [-1, -1, -1, 6, 1, -1]
38+
#array = [17, 18, 5, 4, 6, 1]
39+
# and so on we'll get tmpArray = [18, 6, 6, 6, 1, -1]

0 commit comments

Comments
 (0)