Skip to main content

Posts

Cells with Odd Values in a Matrix

Problem -  https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ Given  n  and  m  which are the dimensions of a matrix initialized by zeros and given an array  indices  where  indices[i] = [ri, ci] . For each pair of  [ri, ci]  you have to increment all cells in row  ri  and column  ci  by 1. Return  the number of cells with odd values  in the matrix after applying the increment to all  indices . Example 1: Input: n = 2, m = 3, indices = [[0,1],[1,1]] Output: 6 Explanation: Initial matrix = [[0,0,0],[0,0,0]]. After applying first increment it becomes [[1,2,1],[0,1,0]]. The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers. Approach -  Iterate over indices and fetch row and column indices.  First loop keep row index constant and increment column index and updated each cell values until it reaches column max size. Repeat same step and keep colum...

Find all the existing paths in graph from source to destination node - BFS and DFS

#!/usr/bin/env python import collections graph = {'A': ['B', 'C'],              'B': ['C', 'D'],              'C': ['D'],              'D': ['C'],              'E': ['F'],              'F': ['C']} #Using DFS algorithm #Ref -   https://www.python.org/doc/essays/graphs/ def find_all_paths_dfs(graph, start, end, path = []):   path = path + [start]   #Reachd end return path   if start == end:         return [path]   #No path found found   if not graph.has_key(start):         return []   paths = []   for node in graph[start]:     if node not in path:       new_paths = find_all_paths_dfs(graph, node, end, path)       for new...

Python Program to Print Directory Structure Recursively

os.walk - Recursively Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). Reference - https://docs.python.org/2/library/os.html Python Program - #!/usr/bin/python3 #Python Program to Print Directory and Files Recursively import os def print_dir(path):   for dirName,subdirList,fileList in os.walk(path):     nw_path = dirName.split('/')     print("|",(len(nw_path))*"---","[",os.path.basename(dirName),"]")     for fl in fileList:       print("|",len(nw_path)*"---","->",str(fl)) if __name__ == "__main__":   path = input("Enter the directory path :-")   print_dir(path) Output - surendra@Surendra:~/workspace/Python_Programs$ python3 recurse_print.py Enter the directory path :-/home/surendra...

Program to validate IPv4 Private Address and print the class

#!/usr/bin/python3  #Program to Validate the IP Address and Print the class of the IPV4 Address #  - 10.0.0.0 - 10.255.255.255 -Class A - NetId 8 Bits , Host Id 24 Bits  #   - 172.16.0.0 - 172.31.255.255 - Class B - NetID 12 Bits, Host ID 20 Bits  #   - 192.168.0.0 - 192.168.255.255 - Class C - NetID 16 Bits , Host ID 16 Bits  #   - 127.0.0.0 to 127.255.255.255 - LocalHost / LoopBack  ''' Steps -         Read Input         Validate IP         split and map the input to integer         From list items 0 to 3 , check for IP Range Conditions ''' import re def validate_ip(ip_addr):  if re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',ip_addr):           lst = list(map(int,ip_addr.split('.')))                      #CLASS A Range - 10.0.0.0 - 10.255.255.255 ...

Best Time to Buy and Sell Stock

Program to Implement - Best Time to Buy and Sell Stock  Say you have an array for which the ith element is the price of a given stock on day i.  If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.  Example 1:  Input: [7, 1, 5, 3, 6, 4]  Output: 5  max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)  Example 2:  In this case, no transaction is done, i.e. max profit = 0.  Input: [7, 6, 4, 3, 1]  Output: 0  '''  class Solution(object):      def maxProfit(self, prices):          """          :type prices: List[int]          :rtype: int          """                 # Brute Force - O(n^2)      ...

Pairwise swap elements of a given linked list by changing links

Pairwise swap elements of a given linked list by changing links -  class Solution(object):          #Iterative Solution          def swapPairs(self, head):          """          :type head: ListNode          :rtype: ListNode          """          if(head is None or head.next is None):              return head                        curr = head.next          prev = head          head = curr                    while(True):              sec = curr.next              curr.next = prev              ...

Program to find Sum of Two Integers without + and -

#Sum of Two Integers Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. class Solution(object):     def getSum(self, a, b):         """         :type a: int         :type b: int         :rtype: int         """         #Works For Positive and Negative          if (a == 0): return b         if (b == 0): return a         if (a == 2147483647 and b == -2147483648): return -1         flag = False         if (a < 0 and b < 0):             a = -a             b = -b             flag = True         mask = 0xffffffff         while (b != 0):       ...

TIC TAC TOE GAME - Simulation of 2 Players

#!/usr/bin/python import random # TIC- TAC TOE GAME Simulation (2 Player , Random Positions) # X | O | X # ---------- # X | O | X # ---------- # O | X | X def fill_tic_tac(): #remove from the position list since this position is occupied #randomly select player and position mark on the matrix position = [0,1,2,3,4,5,6,7,8] box = [0]*(9) flag = True #Marking the Box for i in range(9): #Select Random Position in Matrix pos = random.choice(position) #Delete the position from original position position.remove(pos) #Select the Random player and Insert Player 1 -> 'X' ,Player 2 -> 'O' pl = random.randint(1,2) if(pl == 1): box[pos] = 'X' #Check_Winner here if(check_winner(box,'X')): flag = False print("*** Player 1 - X Is Winner *** ") break else: box[pos] = 'Y' #Check Winner Here if(check_winner(box,'Y')): flag = False print("...

Java program for 2D Array HourGlass Sum

package practice; /* Hacker Rank - 2D Array - HourGlass Problem   * Problem Statement - https://www.hackerrank.com/challenges/2d-array  */ import java.util.*; import java.io.*; public class HourGlass { public static void main(String[] args) { // TODO Auto-generated method stub int a[][]  = new int[6][6]; Scanner in = new Scanner(System.in); int temp_sum,sum = -1000000; //Read 2D Matrix-Array  for(int i = 0; i < 6; i++) { for (int j =0; j < 6;j++) { a[i][j] = in.nextInt(); } }                //Compute the sum of 3*3 sub matrix for(int i = 0; i < 6; i++) { for (int j =0; j < 6;j++) { if(j+2 < 6 && i+2 < 6) { temp_sum = a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2]; if (temp_sum >= sum) { sum = temp_sum; } } } } System.out.println("Sum...

Java Program to Reverse Array

package practice; /* Hacker Rank - Read Integer Array and reverse it -https://www.hackerrank.com/challenges/arrays-ds */ import java.util.*; import java.io.*; public class ReverseArray {         public static void main(String[] args) {                 Scanner in = new Scanner(System.in);                 ArrayList<Integer> elements = new ArrayList<Integer>();                 /* Read the SIZE n elements into Array */                 int size = in.nextInt();                 for (int i = 0; i < size;i++) {                         elements.add(in.nextInt());                 }                 /* Collectio...

Java Program to Sort HashMap

package practice; import java.util.*; /* Java Program to sort Hashmap */ public class HashSort { public static void main(String[] args) { // TODO Auto-generated method stub HashMap <String,Integer> hm = new HashMap<String,Integer>(); hm.put("Suri",10); hm.put("Sam", 01); hm.put("Abhi", 10); //Put the keys into ArrayList and sort it Set <String> keys = hm.keySet(); ArrayList <String> list = new ArrayList<String>(); list.addAll(keys); //Call sort method from Collections Collections.sort(list); //Display Sorted Key's with Values for (String key:list) { System.out.println(key + ":" + hm.get(key)); } } }

Java Collections Demo

package practice; import java.util.*; /* Collection - Arrays/Linked List/Hash Set's/Hash Map */ public class DemoCollection { public static void main(String [] args) { //ArrayList List<String> a1 = new ArrayList<String>(); a1.add("Surendra"); a1.add("Sam"); a1.add("Steven"); a1.add("sam"); System.out.println("Array list "); System.out.print("\t lenghth:" + a1.size()+ a1); //Linkedlist List <String> l1 = new LinkedList<String>(); l1.add("Suri"); l1.add("Sami"); l1.add("Stevie"); l1.add("Suri"); System.out.println(); System.out.println("Linked List"); System.out.print("\t"+l1); //HashSet's Set <Integer> s1 = new HashSet<Integer>(); s1.add(10); s1.add(20); System.out.println(); System.out.println("Hash Set"); System.out.print("\t"+s1); //H...

Time Conversion - Java Program

Java Program to Convert 12HR time to 24HR  Problem - Hacker Rank - https://www.hackerrank.com/challenges/time-conversion import java.io.*; import java.util.*; import java.lang.Object; public class TimeConversion {         /**          * @param args          */ public static void main(String[] args) {         /* Read The time */         Scanner in = new Scanner(System.in);         String input_time = in.next();         //Parse the input         String [] tm = input_time.split(":");         //Extract hh and SS to char array to process AM/PM         int hh = Integer.valueOf(tm[0]);                         char[] secs_str = tm[2].toCharArray();         //AM/PM Time Convertion...

Find second largest number in a list

Problem - https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list #Python Program to find Second Largest number in List with Sort #/usr/bin/python3 n = int(input()) if ( n >= 2 and n <= 10): lst = set(list(map(int,input().split()))) #Set's will avoid duplicated new_lst = list(lst) new_lst.sort() print(new_lst[-2]) #  Python Program to find Second Largest number in List Without Sort #/usr/bin/python3 n = int(input()) a = list(map(int,input().split())) f_num = a[0] s_num = 0; for i in range(1,n):  if(f_num > a[i] and a[i] > s_num) :   s_num = a[i]  if(a[i] > f_num):   s_num = f_num;   f_num = a[i] print("Second Large number is :-",s_num) Input - 5 5 2 10 1 2 Output - Second Large number is :- 5

Nested Lists in Python - List Comprehension

Problem -  https://www.hackerrank.com/challenges/nested-list  - Store stundent information using nested list and retrieve the information , use list comprehension #!/usr/bin/python3 #Read input and append the list to main records list using List Compression records = [[input(),float(input())] for i in range(int(input()))] #sort the list using list compression set will avoid duplicates mk_lst  = sorted(set(x[1] for x in records)) #loop through records and if marks matches with second highest sort and display  the names for name in sorted(x[0] for x in records if x[1] == mk_lst[1]):         print(name) Input   -  5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Output - Berry Harry

Python program to find Matrix Diagonal Difference

Program Statement – Matrix Diagonal Difference You are given a square matrix of size  N × N . Can you calculate the absolute difference of the sums across the main diagonal and the secondary diagonal? https://www.hackerrank.com/challenges/diagonal-difference Program – Python 3 Version mat = [] nrow = int(input()) for i in range(nrow):   mat.extend(list(map(int,input().split()))) #keep extending the array #Main Diagonal Sum indx,pd_sum = 0,0 for i in range(nrow):   pd_sum += mat[indx]   indx += nrow + 1 #Secondary Diagonal Sum indx,sd_sum = nrow-1,0 for i in range(nrow):   sd_sum += mat[indx]   indx += nrow - 1 print(abs(pd_sum – sd_sum)) Input - 3 11 2 4 4 5 6 10 8 -12 Output - 15