PROBLEM 60: Print Pattern
(For best view experience, view in windows version)
Problem Reference : GeeksForGeeks
Author : Ajay ZadDate    : 14/05/2023
Print a sequence of numbers starting with N where A[0] = N, in which  A[i+1] = A[i] - 5,  until A[i] > 0. After that A[i+1] = A[i] + 5  repeat it until A[i] = N.
Example 1:
Input: N = 16
Output: 16 11 6 1 -4 1 6 11 16
Explaination: The value decreases until it 
is greater than 0. After that it increases 
and stops when it becomes 16 again.Example 2:
Input: N = 10
Output: 10 5 0 5 10
Explaination: It follows the same logic as 
per the above example.Solution:
class Solution:
    def pattern(self, N):
        # code here
        l = []
        k = 0
        N1 = N
        while True:
            if k == 0:
                l.append(N)
                N = N - 5
                if N <= 0:
                    k = 1
            else:
                l.append(N)
                N = N + 5
                if N1 == N:
                    l.append(N1)
                    return l
if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        N = int(input())
        
        ob = Solution()
        ans = ob.pattern(N)
        for i in ans:
            print(i, end = " ")
        print()
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 104 
Print a sequence of numbers starting with N where A[0] = N, in which A[i+1] = A[i] - 5, until A[i] > 0. After that A[i+1] = A[i] + 5 repeat it until A[i] = N.
Example 1:
Input: N = 16
Output: 16 11 6 1 -4 1 6 11 16
Explaination: The value decreases until it 
is greater than 0. After that it increases 
and stops when it becomes 16 again.Example 2:
Input: N = 10
Output: 10 5 0 5 10
Explaination: It follows the same logic as 
per the above example.Solution:
class Solution:
    def pattern(self, N):
        # code here
        l = []
        k = 0
        N1 = N
        while True:
            if k == 0:
                l.append(N)
                N = N - 5
                if N <= 0:
                    k = 1
            else:
                l.append(N)
                N = N + 5
                if N1 == N:
                    l.append(N1)
                    return l
if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        N = int(input())
        
        ob = Solution()
        ans = ob.pattern(N)
        for i in ans:
            print(i, end = " ")
        print()
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 104 
 
No comments:
Post a Comment