Showing posts with label for loops. Show all posts
Showing posts with label for loops. Show all posts

Saturday, 22 April 2023

Smaller Sum

 

PROBLEM 59: Smaller Sum

(For best view experience, view in windows version)

Problem Reference : GeeksForGeeks

Author : Ajay Zad
Date    : 22/04/2023


You are given an array arr of n integers. For each index i, you have to find the sum of all integers present in the array with a value less than arr[i].

Example 1:

Input:
n = 3
arr = {1, 2, 3}
Output:
0 1 3
Explanation:
For 1, there are no elements lesser than itself.
For 2, only 1 is lesser than 2.
And for 3, 1 and 2 are lesser than 3, so the sum is 3.

Example 2:

Input:
n = 2
arr = {4, 4}
Output:
0 0
Explanation:
For 4, there are no elements lesser than itself. 
For 4, there are no elements lesser than itself.
There are no smaller elements than 4.

SOLUTION:

from typing import List
class Solution:
    def smallerSum(self, n : int, arr : List[int]) -> List[int]:
        # code here
        ar = set(arr)
        arr1 = list(ar)
        arr1.reverse()
        l = []
        def sum1(i):
            j = arr1.index(i)
            s1 = sum(arr1[j+1:])
            l.append(s1)
        
            
        for i in arr:
            sum1(i)
        return l


class IntArray:
    def __init__(self) -> None:
        pass
    def Input(self,n):
        arr=[int(i) for i in input().strip().split()]#array input
        return arr
    def Print(self,arr):
        for i in arr:
            print(i,end=" ")
        print()


if __name__=="__main__":
    t = int(input())
    for _ in range(t):

        n = int(input())
        arr=IntArray().Input(n)
        obj = Solution()
        res = obj.smallerSum(n, arr)
        
        IntArray().Print(res)
        


Expected Time Complexity:O(n log n)
Expected Space Complexity:O(n)

Constraints:
1 <= n <= 105
0 <= arr[i] <= 109

Saturday, 2 July 2022

Middle School Procedure

 PROBLEM 50: GCD of 2 numbers using Middle School Algorithm approach 


(For best view experience, view in windows version)


Author : Ajay Zad
Date    : 02/07/2022



m = int(input("Enter the M number : "))
n = int(input("Enter the N number : "))
p = []

#Finding Prime numbers 
for i in range(2,20):
    cnt = 0
    for j in range(2,i):
        if i % j == 0:
            cnt = cnt + 1
    if cnt == 0:
        p.append(i)

#Finding prime factors of M
l = []
a = 0
while m >= 1:
    if a == len(p) - 1:
        break
    if m % p[a] == 0:
        l.append(p[a])
        m = m / p[a]
    else:
        a = a + 1
print("Factors of number M : ",l)      

 
#Finding prime factors of N        
s = []
b = 0
while n >= 1:
    if b == len(p) - 1:
        break
    if n % p[b] == 0:
        s.append(p[b])
        n = n / p[b]
    else:
        b = b + 1
print("Factors of number N :",s)


#Finding common factors of M & N
m = []
for i in p:
    if i in l and i in s:
        ll = l.count(i)
        ss = s.count(i)
        mi = min(ll,ss)
        pro = 1
        for j in range(0,mi):
            pro = pro * i
        m.append(pro)
    
    
pro = 1
for i in m:
    pro = pro * i
    
print("GCD of M and N = ",pro)
    



The above program is in Python language




Output : 

Enter the M number : 32 
Enter the N number  : 80

Factors of number M :  [2, 2, 2, 2, 2]
Factors of number N  :  [2, 2, 2, 2, 5]

GCD of M and N =  16


Tuesday, 19 April 2022

Matrix Rotate Problem !!!

PROBLEM 49: Matrix Rotate Problem

A program to rotate a square matrix by 90° anti-clockwise direction. (Interview Question)

(For best view experience, view in windows version)


Author : Ajay Zad
Date    : 19/04/2022


#include<stdio.h>
void main()
{
        int i,j,r,c,m,n;
        printf("Enter the size for Row :");
        scanf("%d",&r);
        
        printf("Enter the size for Column :");
        scanf("%d",&c);
        
        int matrix1[r][c],matrix2[r][c];
        
        printf("Enter the elements in the matrix :\n");
        for(i = 0 ; i < r ; i++)
        {
            for(j = 0 ; j < c ; j++)
            {
                scanf("%d",&matrix1[i][j]);
            }
        }

        
        printf("\n\n");
        
        for(i = 0 ; i < r ; i++)
        {
            for(j = 0 ; j < c ; j++)
            {
                matrix2[i][j] = matrix1[j][i];
            }
        }

        
        m = 0;
        for(i = (r-1); i >= 0 ; i--)
        {
            n = 0;
            for( j = 0 ; j < c ; j++)
            {
                matrix1[m][n] = matrix2[i][j];
                n++;
            }
            m++;
        }

       printf("Matrix after 90 degree's rotation : \n"); 
        for(i = 0 ; i < r ; i++)
        {
            for(j = 0 ; j < c ; j++)
            {
                printf("%d\t",matrix1[i][j]);
            }
            printf("\n");
        }
        
}

The above code is in C language. 

Output :
Enter the size for Row : 3
Enter the size for Column : 3
Enter the elements in the matrix :
1
2
3
4
5
6
7
8
9

The original form of the matrix will be as follow :
1    2    3
4    5    6
7    8    9

Matrix after 90 degree's rotation :
3    6    9
2    5    8
1    4    7
 

Friday, 8 April 2022

Array Rotate Problem !!!

 PROBLEM 48: Array Rotate 


A program to rotate 'N' number of elements in an array depending on the size of the rotate. Rotation to be considered from both the ends of an array. (Without using Built-in functions) (INTERVIEW QUESTION)

(For best view experience, view in windows version)


Author - Ajay Zad

Date     - 08/04/2022


n = int(input("Enter the size of the array :"))

m = int(input("Enter the size of rotation :"))

l = []

for i in range(0,n):

        a = int(input("Enter the elements in the array :"))

        l.append(a)

x = 1

while x == 1:

        d = input("Enter the direction for rotation Right(r) or Left(l):")

        if d == 'l':

            l2 = list(l)        

            j = 1

            for i in range(m-1,-1,-1):

                l2[n-j] = l[i]   

                j = j + 1

            j = 0

            for i in range(m,n):

                 l2[j] = l[m+j]

                 j = j + 1

            print(l2)

            l = l2[:]        

        elif d == 'r':

            l2 = list(l)

            j = 0

            for i in range(m-1,-1,-1):

                l2[i] = l[n-(j+1)]

                j = j + 1

            j = 0

            for i in range(m,n):

                l2[m+j] = l[j]

                j = j + 1

            print(l2)

            l = l2[:]

        else:

            print("Enter the correct option")

        x = int(input("Enter 1 to continue or press any other number to exit: "))

   

The above code is in Python language.


Input:

Enter the size of the array : 8
Enter the size of rotation   : 4

Enter the elements in the array : 1
Enter the elements in the array : 2
Enter the elements in the array : 3
Enter the elements in the array : 4
Enter the elements in the array : 5
Enter the elements in the array : 6
Enter the elements in the array : 7
Enter the elements in the array : 8

Enter the direction for rotation Right(r) or Left(l): l
[5, 6, 7, 8, 1, 2, 3, 4]

Enter 1 to continue or press any other number to exit: 1

Enter the direction for rotation Right(r) or Left(l): r
[1, 2, 3, 4, 5, 6, 7, 8]

Enter 1 to continue or press any other number to exit: 2












  



Thursday, 17 March 2022

Minimum Number of Jumps Problem !!!

 PROBLEM 47:  Minimum Number of Jumps


A Program to find the minimum number of jumps to reach the end of the array (starting from the first element). (Interview Question)


Author - Ajay Zad
Date    - 17/03/2022


import sys
n = int(input("Enter the value for n :"))
l = []
for i in range(0,n):
    m = int(input("Enter the elements in the array :"))
    l.append(m)

i = 0
j = l[0]
cnt = 0
cnt1 = 0
while i < n :
    while j > 0:
        j = j - 1
        cnt = cnt + 1
    else:
        try:
            j = l[cnt]
            #cnt1 will keep track of no. of jumps
            cnt1 = cnt1 + 1
        except:
            print("Number of jumps required = ",cnt1)
            sys.exit()
    i = cnt
print("Number of jumps required = ",cnt1)

The above code is in Python Language.


Input :
Enter the value for n : 5
Enter the elements in the array : 1
Enter the elements in the array : 2
Enter the elements in the array : 2
Enter the elements in the array : 3
Enter the elements in the array : 4


Output :
Number of jumps required = 3


Tuesday, 15 March 2022

Repetition Of All Numbers Problem !!!

 PROBLEM 46: Repetition Of All Numbers


A Program to find out number of times the elements are repeated in the array.

(Interview Question)


Author - Ajay Zad

Date   - 15-03-2022


n = int(input("Enter the size of the array :"))

l = []

for i in range(0,n):

    m = int(input("Enter the elements in the array (repeat the values) :"))

    l.append(m)

    

s = set(l)

l1 = list(s)

l1.sort()


for i in range(0,len(l1)):

    cnt = 0

    for j in range(0,n):

        if l1[i] == l[j]:

            cnt = cnt + 1

    print("Number ",l1[i]," is repeated for = ",cnt," times")

       

The above code is in python language.

Input : 

Enter the size of the array : 5 

Enter the elements in the array (repeat the values) :1

Enter the elements in the array (repeat the values) :2

Enter the elements in the array (repeat the values) :1

Enter the elements in the array (repeat the values) :3

Enter the elements in the array (repeat the values) :2


Output: 

Number  1  is repeated for =  2  times

Number  2  is repeated for =  1  times

Number  3  is repeated for =  2  times

Monday, 14 March 2022

Prime Problem !!!

 PROBLEM 45: Prime 


Program to find out all the prime numbers from the range of 0 to n. 


 Name - Ajay Zad

 Date - 14/03/2022 


n = int(input("Enter the value for n :"))

cnt = 0 

print("The Prime numbers are :")

for i in range(2,n+1):

    for j in range(2,i):

        if i % j == 0:   

            cnt = cnt + 1

        

    if cnt == 0:

        print(i)

    cnt = 0




Input:

Enter the value for n : 

10


Output :

The Prime numbers are :

2

3

5

7

Friday, 11 March 2022

Repetition Problem !!!

PROBLEM 44:  Repetition


A Program to find out the most repeated number in the array. (Without using built-in functions)

(Interview Question)


 Author - Ajay Zad 

 Date     - 11/03/2022 


n = int(input("Input the size of the array :"))

l = []

s = set()

for i in range(0,n):

    ele = int(input("Enter the elements in the array :"))

    l.append(ele)

    #Adding no. in set as it doesn't store duplicates

    s.add(ele)

    

cnt = 0

cnt1 = 0

l2 = list(s)

for i in range(0,len(l2)):

    cnt = 0

    for j in range(0,n):

        #Comparing for equality 

        if l2[i] == l[j]:

            cnt = cnt + 1

            #Condition for counter 

            if cnt > cnt1:

                cnt1 = cnt

                m_no = l2[i]

print("The number with highest repetition : ",m_no)


Input :

Input the size of the array : 5

Enter the elements in the array : 1

Enter the elements in the array : 2

Enter the elements in the array : 2

Enter the elements in the array : 3

Enter the elements in the array : 2


Output :

The number with highest repetition : 2


                


                

    

Thursday, 10 March 2022

Missing Number Problem !!!

 PROBLEM 43 : Missing Number 

A Program to find out the missing number from a range of 0-N numbers in a series. 

(Interview Question)


Author - Ajay Zad

Date   - 10/03/2022 


import sys    

n = int(input("Enter the value for n : "))

l = []

for i in range(1,n):

    n1 = int(input("Enter the value less than or equal to 'n' without repeating the values :"))

    l.append(n1)

    

l.sort()

j = 1

for i in range(0,n-1):

    if j != l[i]:

        print("The missing number is ",j)

        sys.exit()

    j = j + 1

    

print("The missing number is ",n)


                                                                    OR


n = int(input("Enter the value for n : "))

l = []

sum = 0

for i in range(1,n):

    n1 = int(input("Enter the value less than or equal to 'n' without repeating the values :"))

    l.append(n1)

    sum = sum + n1

    

sum1 = 0    

for i in range(1,n+1):

    sum1 = sum1 + i

    

print("The missing number is ",(sum1-sum))


The above code is in Python language.


Input :

Enter the value for n : 5

Enter the value less than or equal to 'n' without repeating the values : 3

Enter the value less than or equal to 'n' without repeating the values : 1

Enter the value less than or equal to 'n' without repeating the values : 5

Enter the value less than or equal to 'n' without repeating the values : 2


Output :

The missing number is 4

Tuesday, 8 March 2022

Diamond Problem !!!

 PROBLEM 42 : Diamond 


A program to display the shape of  a diamond using asterisk (*) symbol for 'N' number of lines 


Author - Ajay Zad

date   - 08/03/2022 


# n defines number of lines     

n = int(input("Enter for n :"))

stars = 1

spaces = n     

for i in range(0,n):

    #loop for implementing spaces

    for j in range(spaces,0,-1):

        print(" ",end="")

    #loop for printing stars

    for k in range(0,stars):

        print("*",end="")

    print()

    stars = stars + 2

    spaces = spaces - 1

    

stars = (n*2) - 1

spaces = 1

for i in range(0,n):

    for j in range(0,spaces):

        print(" ",end="")

    for k in range(stars,0,-1):

        print("*",end="")

    print()

    stars = stars - 2

    spaces = spaces + 1



The above code is in Python language.


Input :

Enter for n : 4


Output :

              *

        *    *    *

    *    *    *    *    *

 *    *    *    *    *    *

    *    *    *    *    *

        *    *    *

              *

Monday, 7 March 2022

First & Last Problem !!!

PROBLEM 41 : First & Last


A program to find whether the first digit of  the input and the last digit of the input are same or not. 




 Author - Ajay Zad
 date   - 07/03/2022 

num = int(input("Enter the number :"))
#Converting from int data type to string data type
string = str(num)         
#Finding the length of the string           
length = len(string)       
#Comparing for equality          
if  string[0] == string[length-1]:     
    print("Both the digits are same")
else:
    print("Both the digits are not same")



Input :
Enter the number : 10011

Output :
Both the digits are same


Input :
Enter the number : 10022

Output:
Both the digits are not same 



Sunday, 19 December 2021

Team Problem !!!

 PROBLEM 40: Team


Problem Reference: Codeforces 


One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.

This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.


Input:

The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.


Output:

Print a single integer — the number of problems the friends will implement on the contest.


Solution: 


  1. n = int(input())
  2. k=0
  3. for i in range(0,n):
  4. a , b , c = input().split()
  5. if(int(a) == 1 and int(b) == 1 and int(c) == 1):
  6. k = k + 1
  7. elif(int(a) == 0 and int(b) == 1 and int(c) == 1):
  8. k = k + 1
  9. elif(int(a) == 1 and int(b) == 0 and int(c) == 1):
  10. k = k + 1
  11. elif(int(a) == 1 and int(b) == 1 and int(c) == 0):
  12. k = k + 1
  13. else:
  14. pass
  15. print(k)



The above solution is in python language.


Examples
input
3
1 1 0
1 1 1
1 0 0
output
2
input
2
1 0 0
0 1 1
output
1

Saturday, 18 December 2021

Sereja and Dima Problem !!!

 PROBLEM 39: Sereja and Dima


Problem Reference: Codeforces


Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.

Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.

Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.


Input:

The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.


Output:

On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.


Soutions:


  1. n = int(input())
  2. a = [int(a) for a in input().split()]
  3. s = []
  4. d = []
  5. i = 0
  6. j = len(a) - 1
  7. t = 0
  8. while i <= j :
  9. if t == 0:
  10. if a[i] > a[j]:
  11. s.append(a[i])
  12. i = i + 1
  13. else:
  14. s.append(a[j])
  15. j = j - 1
  16. t = 1
  17. else:
  18. if a[i] > a[j]:
  19. d.append(a[i])
  20. i = i + 1
  21. else:
  22. d.append(a[j])
  23. j = j - 1
  24. t = 0
  25.  
  26. print(sum(s),sum(d))


The above solution is in python language



Examples
input
4
4 1 2 10
output
12 5
input
7
1 2 3 4 5 6 7
output
16 12

Friday, 17 December 2021

Do Not Be Distracted Problem !!!

 PROBLEM 38: Do Not Be Distracted!


Problem Reference: Codeforces 


Polycarp has  tasks. Each task is designated by a capital letter of the Latin alphabet.

The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.

Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.

For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".

If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".

Help Polycarp find out if his teacher might be suspicious.


Input:

The first line contains an integer  (). Then  test cases follow.

The first line of each test case contains one integer () — the number of days during which Polycarp solved tasks.

The second line contains a string of length , consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.


Output:

For each test case output:

  • "YES", if the teacher cannot be suspicious;
  • "NO", otherwise.

You may print every letter in any case you want (so, for example, the strings yEsyesYes and YES are all recognized as positive answer).


Solution:


  1. t = int(input())
  2. while 0 < t :
  3. n = int(input())
  4. s = input()
  5. a = set()
  6. i = 1
  7. while i < len(s):
  8. if s[i-1] != s[i]:
  9. a.add(s[i-1])
  10. if s[i] in a:
  11. print("NO")
  12. break
  13. i = i + 1
  14. if s[i-1] not in a:
  15. print("YES")
  16. t = t - 1


The above solution is in python language.


Example
input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
output
NO
NO
YES
YES
YES

Rearrange an array with O(1) extra space

  PROBLEM 61:  Rearrange an array with O(1) extra space (For best view experience, view in windows version) Problem Reference : GeeksForGeek...