Moo - Google Top Interview Questions
Problem Statement :
You are given a string cows representing the initial conditions of some cows. Each cow can take one of three values: "L", meaning the cow is charging to the left. "R", meaning the cow is charging to the right. "@", meaning the cow is standing still. Cows charging on a direction will pick up other cows unless the cow receives a force from the opposite direction. Then, it will stand still. Return the orientation of each cow when the cow stop charging. Constraints n ≤ 100,000 where n is the length of cows Example 1 Input cows = "@L@R@@@@L" Output "LL@RRRLLL" Example 2 Input cows = "@@R@@@L@L" Output "@@RR@LLLL"
Solution :
Solution in C++ :
void process(string& cows, int i, int j) {
char l = cows[i], r = cows[j];
if ((l == '@' || l == 'L') && (r == '@' || r == 'R')) return;
if ((l == '@' || l == 'L') && r == 'L') {
while (i < j) cows[i++] = 'L';
} else if (l == 'R' && (r == '@' || r == 'R')) {
while (i <= j) cows[i++] = 'R';
} else {
while (i<j) {
cows[i++] = 'R';
cows[j--] = 'L';
}
}
}
string solve(string cows) {
for (int i=0, j=0; j<cows.size(); j++) {
if (cows[j] != '@' || j == cows.size() - 1) {
process(cows, i, j);
i = j;
}
}
return cows;
Solution in Java :
import java.util.*;
class Solution {
public String solve(String cows) {
int R = -1;
// this variable is used to track the index of the character "R" so that when I find the
// character "L" I can perform some sort of collide -1 means R is not initialized
int last_event = 0;
// this variable is used to represent the "last_event" so in the case "L@R@@L" my last event
// will be at index 2. This will help me track which @ to cover when I find "L"
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cows.length(); i++) {
// if R is not initialized that means that when I see L then everything to the left of
// it is going to be charging left now
if (cows.charAt(i) == 'L' && R == -1) {
for (int j = 0; j < i - last_event + 1; j++) {
sb.append('L');
}
// I change the last event
last_event = i + 1;
}
// if R is already initialized and we encounter another R we turn all the cows between
// it into R case: R@@@@@R@L everything between that will turn into R My intuition is to
// simply attack all the RL collisions using halves, so it's important that I find the
// closest R and L when these collisions occur.
if (cows.charAt(i) == 'R' && R != -1) {
for (int j = 0; j < i - R; j++) {
sb.append('R');
}
R = i;
}
// If we encountered an 'R' and it's not initialized we will set it to the current
// index.
if (cows.charAt(i) == 'R' && R == -1) {
// We append those still cows in cases like this:
//@@@R@L
//@L@@R
for (int j = 0; j < i - last_event; j++) {
sb.append('@');
}
R = i;
}
// This is when the action happens. I've found the closest R and closest L. If (i-R) % 2
// == 1 we will NOT append a still cow in the middle.
if (cows.charAt(i) == 'L' && R != -1) {
// cases like this:
// L@@R
if ((i - R) % 2 == 1) {
for (int j = 0; j < (i - R) / 2 + 1; j++) {
sb.append('R');
}
for (int j = 0; j < (i - R) / 2 + 1; j++) {
sb.append('L');
}
}
// cases like this:
// L@@@R
else {
for (int j = 0; j < (i - R) / 2; j++) {
sb.append('R');
}
sb.append('@');
for (int j = 0; j < (i - R) / 2; j++) {
sb.append('L');
}
}
// set last_event
last_event = i + 1;
// R will not be initialized anymore because the collision occurs.
R = -1;
}
}
// after we finish iterating through the string, we need to take care of a couple more cases
// in this case if we have R@@@@@ in the back of the string we need to change everything
// after 'R' to 'R'. We can check if case exists by seeing if R is initialized after the for
// loop
if (R != -1) {
sb.append('R');
for (int i = cows.length() - 1; i >= 0; i--) {
if (cows.charAt(i) != '@')
break;
sb.append('R');
}
}
// or if the case is simply RL@@@@@ we need to append everything in the back.
else {
for (int i = cows.length() - 1; i >= 0; i--) {
if (cows.charAt(i) != '@')
break;
sb.append('@');
}
}
// return the final string
return sb.toString();
}
}
Solution in Python :
class Solution:
def solve(self, cows):
Lq = deque()
Rq = deque()
cows = list(cows)
# appending the initiators --> R's and L's into a queue
for ind, c in enumerate(cows):
if c == "L":
Lq.append((ind, 0))
if c == "R":
Rq.append((ind, 0))
# L filling all the @'s to its left while appending the distance of each @ from the initiator
while Lq:
cur, dist = Lq.popleft()
cows[cur] = "L{}".format(dist)
if cur > 0 and cows[cur - 1] == "@":
Lq.append((cur - 1, dist + 1))
# print(" ".join(cows))
# R's chance to fill / correct the blocks filled by L
stopDist = isMid = n = len(cows)
prev = -1
while Rq:
cur, dist = Rq.popleft()
if prev >= cur:
continue
# non conflicting @
while cur < n and cows[cur][0] != "L":
cows[cur], cur = "R", cur + 1
if cur >= n:
break
# 'R' is getting to know how many Li's it need to overwrite
Ldist = int(cows[cur][1:])
stopDist, isMid = divmod(Ldist, 2)
dist = 0
# 'R' overwriting the Li's till its part
while cur < n and dist < stopDist:
cows[cur] = "R"
dist, cur = dist + 1, cur + 1
# correcting the middle '@'
if cur < n and isMid == 1:
cows[cur] = "@"
prev = cur
return "".join([c[0] for c in cows])
View More Similar Problems
Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →Print in Reverse
Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing
View Solution →