Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
557 views
in Online Assessments by Expert (46,090 points) | 557 views

2 Answers

0 like 0 dislike
Best answer

Car parking
Current state of car parking is stored in array current
-1 denotes a pillar,0-denotes a empty space,a positive integer denotes car number at spot.

 

Desired - array denoting ideal parking positioning of cars

 

1 move- car forward or backward to an empty space
Find minimum moves for car to reach desired positions.
Car cannot move or go through pillars.Car also cannot go over other cars.
Return -1 if desired cannot be achieved.

 

example
N-size of array
current=[-1,1,0,2]
desired=[-1,0,1,2]
output -1
move car 1 from position 1 to position 2

 

Sample-2

 

N- 4
current -0 1 2 0
desired- 1 2 0 0

 

output-2
move car 1 from position 2 to position 1.
[1 0 2 0]
move car 2 from position 2 to position 1.
[1 2 0 0]

 

Other test cases

 

N-7
current- [ 0 0 0 -1 7 -1 6 ]
desired -[ 0 0 0 -1 7 -1 6 ]

 

output=0

 

N-8
current- [ -1 7 5 -1 -1 -1 2 0 ]
desired -[ -1 7 5 -1 -1 -1 0 2]

 

output=1

 

N-8
current - [0 1 -1 5 8 6 0 2]
desired - [1 0 -1 5 8 0 2 6]

 

output= -1

 

function
def minimum_moves( N,current,desired )

by Expert (46,090 points)
0 like 0 dislike
cur=[-1,1,0,2]
des=[-1,0,1,2]

if Counter(cur)!=Counter(des):
    return -1

index, limit, res = {j:i for i,j in enumerate(cur)}, -1, 0      
for i,j in enumerate(des):
    if j==0:
        continue
    
    if j<0:
        if cur[i]!=-1 or limit>i:
            return -1
        limit=i
        continue
    
    if index[j]<limit:
        return -1
    res+=abs(index[j]-i)    
    limit=max(index[j],i)

 return res
by Expert (46,090 points)