Leetcode 1115: Print FooBar Alternately

grid47
grid47
Exploring patterns and algorithms
Jul 18, 2024 6 min read

You are given a class FooBar with two methods: foo() and bar(). These methods are called concurrently by two threads. One thread calls foo() while the other calls bar(). You need to modify the program to ensure that the output alternates between ‘foo’ and ‘bar’, and ‘foobar’ is printed exactly n times. The threads should alternate their execution such that foo() is printed first, followed by bar(), and this pattern should continue for n times.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n` representing the number of times the pattern 'foobar' should be printed.
Example: Input: n = 3
Constraints:
• 1 <= n <= 1000
Output: The output should be the string 'foobar' repeated `n` times, with each 'foo' and 'bar' printed by different threads in alternating order.
Example: Output: 'foobarfoobarfoobar'
Constraints:
• The two threads should print 'foo' and 'bar' in alternating order, starting with 'foo'.
Goal: Ensure that the two threads alternate between printing 'foo' and 'bar', starting with 'foo', for `n` times.
Steps:
• Use two mutexes to control the execution order of the threads.
• Thread A prints 'foo', and thread B prints 'bar'. Thread A should print first, then thread B, and the alternation continues for `n` times.
Goal: Ensure that both threads print their respective strings in the correct order without overlap.
Steps:
• Threads A and B must alternate printing 'foo' and 'bar'.
• The total number of 'foobar' printed must be exactly `n`.
Assumptions:
• Threads are scheduled asynchronously, so thread A and thread B may not execute in any specific order without synchronization.
Input: Input: n = 1
Explanation: In this case, thread A calls `foo()` and thread B calls `bar()`. The expected output is 'foobar' because thread A prints 'foo' first, followed by thread B printing 'bar'.

Input: Input: n = 2
Explanation: Here, the expected output is 'foobarfoobar' because the pattern 'foo' followed by 'bar' should repeat twice.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus