├── 2d-array.js ├── a-very-big-sum.swift ├── african-cities.sql ├── alien-username.py ├── arrays-ds.swift ├── asian-population.sql ├── average-population-of-each-continent.sql ├── average-population.sql ├── bash-tutorials---a-personalized-echo.sh ├── bash-tutorials---arithmetic-operations.sh ├── bash-tutorials---comparing-numbers.sh ├── bash-tutorials---compute-the-average.sh ├── bash-tutorials---getting-started-with-conditionals.sh ├── bash-tutorials---looping-and-skipping.sh ├── bash-tutorials---looping-with-numbers.sh ├── bash-tutorials---more-on-conditionals.sh ├── bash-tutorials---the-world-of-numbers.sh ├── bash-tutorials-lets-echo.sh ├── birthday-cake-candles.swift ├── chocolate-feast.cpp ├── compare-the-triplets.swift ├── counting-valleys.js ├── ctci-array-left-rotation.js ├── ctci-bubble-sort.js ├── ctci-ice-cream-parlor.js ├── ctci-ransom-note.js ├── detecting-valid-latitude-and-longitude.py ├── diagonal-difference.swift ├── find-a-word.py ├── find-hackerrank.py ├── find-substring.py ├── fizzbuzz.py ├── game-of-thrones.py ├── gem-stones.py ├── grading.js ├── hackerrank-language.py ├── hackerrank-tweets.py ├── halloween-party.py ├── ip-address-validation.py ├── japan-population.sql ├── japanese-cities-attributes.sql ├── japanese-cities-name.sql ├── jumping-on-the-clouds.js ├── lonely-integer.py ├── mark-and-toys.js ├── mini-max-sum.swift ├── pairs.py ├── plus-minus.swift ├── population-density-difference.sql ├── repeated-string.js ├── revising-aggregations-sum.sql ├── revising-aggregations-the-average-function.sql ├── revising-aggregations-the-count-function.sql ├── revising-the-select-query-2.sql ├── revising-the-select-query.sql ├── saying-hi.py ├── select-all-sql.sql ├── select-by-id.sql ├── sherlock-and-squares.py ├── simple-array-sum.swift ├── sock-merchant.js ├── solve-me-first.py ├── split-number.py ├── staircase.swift ├── the-love-letter-mystery.py ├── time-conversion.js ├── two-strings.js ├── uk-and-us-2.py ├── uk-and-us.py ├── utopian-identification-number.py ├── utopian-tree.py ├── valid-pan-format.py ├── weather-observation-station-1.sql ├── weather-observation-station-2.sql ├── weather-observation-station-3.sql └── weather-observation-station-4.sql /2d-array.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Counts the maximum sum of all hourglass patterns in a 2D array. 4 | // 5 | // https://www.hackerrank.com/challenges/2d-array 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function hourglassSum(arr) { 34 | let maximumSum = -Infinity; 35 | 36 | for (let y = 1; y < arr.length - 1; y += 1) { 37 | for (let x = 1; x < arr[0].length - 1; x += 1) { 38 | const sum = arr[y - 1][x - 1] + 39 | arr[y - 1][x] + 40 | arr[y - 1][x + 1] + 41 | arr[y][x] + 42 | arr[y + 1][x - 1] + 43 | arr[y + 1][x] + 44 | arr[y + 1][x + 1]; 45 | 46 | if (sum > maximumSum) { 47 | maximumSum = sum; 48 | } 49 | } 50 | } 51 | 52 | return maximumSum; 53 | } 54 | 55 | function main() { 56 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 57 | let arr = Array(6); 58 | 59 | for (let i = 0; i < 6; i++) { 60 | arr[i] = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10)); 61 | } 62 | 63 | let result = hourglassSum(arr); 64 | ws.write(result + "\n"); 65 | ws.end(); 66 | } 67 | -------------------------------------------------------------------------------- /a-very-big-sum.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Prints the sum of the array's elements, some of which may be very large. 4 | // 5 | // https://www.hackerrank.com/challenges/a-very-big-sum 6 | 7 | import Foundation 8 | 9 | _ = readLine() 10 | 11 | let result = readLine()! 12 | .components(separatedBy: " ") 13 | .flatMap { Int($0) } 14 | .reduce(0, +) 15 | 16 | print(result) 17 | -------------------------------------------------------------------------------- /african-cities.sql: -------------------------------------------------------------------------------- 1 | -- Lists all countries in Africa. 2 | -- https://www.hackerrank.com/challenges/african-cities 3 | 4 | SELECT CITY.NAME 5 | FROM CITY, COUNTRY 6 | WHERE CITY.COUNTRYCODE = COUNTRY.CODE 7 | AND CONTINENT = 'Africa' 8 | -------------------------------------------------------------------------------- /alien-username.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Identifies whether fictional alien usernames are valid. 5 | 6 | https://www.hackerrank.com/challenges/alien-username 7 | """ 8 | 9 | import re 10 | 11 | 12 | def validate_usernames(usernames): 13 | """Prints 'VALID' for valid usernames, 'INVALID' otherwise.""" 14 | pattern = re.compile('^[_\.]\d+[a-z]*_?$', re.IGNORECASE) 15 | 16 | for username in usernames: 17 | print('VALID' if pattern.match(username) else 'INVALID') 18 | 19 | 20 | if __name__ == '__main__': 21 | username_count = int(input()) 22 | usernames = (input() for _ in range(username_count)) 23 | validate_usernames(usernames) 24 | -------------------------------------------------------------------------------- /arrays-ds.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Prints an array of integers in reverse order on a single line. 4 | // 5 | // https://www.hackerrank.com/challenges/arrays-ds 6 | 7 | import Foundation 8 | 9 | _ = readLine() 10 | 11 | readLine()! 12 | .components(separatedBy: " ") 13 | .flatMap { Int($0) } 14 | .reversed() 15 | .forEach { print($0, terminator: " ") } 16 | -------------------------------------------------------------------------------- /asian-population.sql: -------------------------------------------------------------------------------- 1 | -- Sums the population of all countries in Asia. 2 | -- https://www.hackerrank.com/challenges/asian-population 3 | 4 | SELECT SUM(CITY.POPULATION) 5 | FROM CITY, COUNTRY 6 | WHERE CITY.COUNTRYCODE = COUNTRY.CODE 7 | AND CONTINENT = 'Asia' 8 | -------------------------------------------------------------------------------- /average-population-of-each-continent.sql: -------------------------------------------------------------------------------- 1 | -- Finds the average population of cities in each continent. 2 | -- https://www.hackerrank.com/challenges/average-population-of-each-continent 3 | 4 | SELECT CONTINENT, FLOOR(AVG(CITY.POPULATION)) 5 | FROM CITY, COUNTRY 6 | WHERE CITY.COUNTRYCODE = COUNTRY.CODE 7 | GROUP BY CONTINENT 8 | -------------------------------------------------------------------------------- /average-population.sql: -------------------------------------------------------------------------------- 1 | -- Calculates the average population of cities, rounded down. 2 | -- https://www.hackerrank.com/challenges/average-population 3 | 4 | SELECT FLOOR(AVG(POPULATION)) 5 | FROM CITY 6 | -------------------------------------------------------------------------------- /bash-tutorials---a-personalized-echo.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Echoes the provided name. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---a-personalized-echo 5 | 6 | read name 7 | echo "Welcome $name" 8 | -------------------------------------------------------------------------------- /bash-tutorials---arithmetic-operations.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Evaluates a given numerical expression to three decimal places. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations 5 | 6 | read input 7 | printf "%.3f\n" `echo "$input" | bc -l` 8 | -------------------------------------------------------------------------------- /bash-tutorials---comparing-numbers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Given two numbers X and Y, identifies if X < Y, X > Y, or X == Y. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---comparing-numbers 5 | 6 | read X 7 | read Y 8 | 9 | if (( $X < $Y )); then 10 | echo 'X is less than Y' 11 | elif (( $X > $Y )); then 12 | echo 'X is greater than Y' 13 | else 14 | echo 'X is equal to Y' 15 | fi 16 | -------------------------------------------------------------------------------- /bash-tutorials---compute-the-average.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Computes the average of three numbers, to three decimal places. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---compute-the-average 5 | 6 | sum=0 7 | read N 8 | 9 | for i in $(seq 1 $N); do 10 | read number 11 | sum=$(( $sum + $number )) 12 | done 13 | 14 | printf "%.3f\n" `echo "$sum / $N" | bc -l` 15 | -------------------------------------------------------------------------------- /bash-tutorials---getting-started-with-conditionals.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Print "YES" given a 'Y' or 'y', "NO" otherwise. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---getting-started-with-conditionals 5 | 6 | read input 7 | 8 | if [[ "$input" == 'Y' || "$input" == 'y' ]]; then 9 | echo 'YES' 10 | else 11 | echo 'NO' 12 | fi 13 | -------------------------------------------------------------------------------- /bash-tutorials---looping-and-skipping.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Prints the odd numbers between 1 and 99. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---looping-and-skipping 5 | 6 | for i in {1..99..2}; do 7 | echo $i 8 | done 9 | -------------------------------------------------------------------------------- /bash-tutorials---looping-with-numbers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Prints numbers between 1 and 50. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---looping-with-numbers 5 | 6 | for i in {1..50}; do 7 | echo $i 8 | done 9 | -------------------------------------------------------------------------------- /bash-tutorials---more-on-conditionals.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Determines if a triangle is scalene, equilateral, or isosceles. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---more-on-conditionals 5 | 6 | read X 7 | read Y 8 | read Z 9 | 10 | if [[ "$X" == "$Y" && "$X" == "$Z" ]]; then 11 | echo 'EQUILATERAL' 12 | elif [[ "$X" == "$Y" || "$X" == "$Z" || "$Y" == "$Z" ]] ; then 13 | echo 'ISOSCELES' 14 | else 15 | echo 'SCALENE' 16 | fi 17 | -------------------------------------------------------------------------------- /bash-tutorials---the-world-of-numbers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Given two integers, finds their sum, difference, product and quotient. 4 | # https://www.hackerrank.com/challenges/bash-tutorials---the-world-of-numbers 5 | 6 | read X 7 | read Y 8 | 9 | echo "$(( $X + $Y ))" 10 | echo "$(( $X - $Y ))" 11 | echo "$(( $X * $Y ))" 12 | echo "$(( $X / $Y ))" 13 | -------------------------------------------------------------------------------- /bash-tutorials-lets-echo.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Introductory Bash script which simply prints "HELLO" to the terminal. 4 | # https://www.hackerrank.com/challenges/bash-tutorials-lets-echo 5 | 6 | echo 'HELLO' 7 | -------------------------------------------------------------------------------- /birthday-cake-candles.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Finds the number of occurrences of the largest value in a given array. 4 | // 5 | // https://www.hackerrank.com/challenges/birthday-cake-candles 6 | 7 | import Foundation 8 | 9 | _ = readLine() 10 | let numbers = readLine()!.components(separatedBy: " ").flatMap { Int($0) } 11 | let maxNumber = numbers.max() 12 | let occurrences = numbers.filter { $0 == maxNumber } 13 | print(occurrences.count) 14 | -------------------------------------------------------------------------------- /chocolate-feast.cpp: -------------------------------------------------------------------------------- 1 | // Determines how many chocolates of price $C can be purchased given a $N bill. 2 | // An additional chocolate is free for every M wrappers traded. 3 | // 4 | // https://www.hackerrank.com/challenges/chocolate-feast 5 | 6 | #include 7 | using namespace std; 8 | 9 | int main() { 10 | int t, n, c, m; 11 | cin >> t; 12 | 13 | while (t--) { 14 | cin >> n >> c >> m; 15 | int answer = n / c; 16 | int wrappers = answer; 17 | 18 | // Spend wrappers for additional chocolates. 19 | while (wrappers >= m) { 20 | wrappers -= m; 21 | 22 | // Eat chocolate, produce new wrapper. 23 | answer++; 24 | wrappers++; 25 | } 26 | 27 | cout << answer << endl; 28 | } 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /compare-the-triplets.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Compares two tuples, assigning a point for each element greater than the other. 4 | // 5 | // https://www.hackerrank.com/challenges/compare-the-triplets 6 | 7 | import Foundation 8 | 9 | let a = readLine()!.components(separatedBy: " ").flatMap { Int($0) } 10 | let b = readLine()!.components(separatedBy: " ").flatMap { Int($0) } 11 | let aScore = zip(a, b).filter(>).count 12 | let bScore = zip(b, a).filter(>).count 13 | print(aScore, bScore) 14 | -------------------------------------------------------------------------------- /counting-valleys.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Counts the number of valleys traversed (consecutive elevation dips below 0). 4 | // 5 | // https://www.hackerrank.com/challenges/counting-valleys 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function countingValleys(n, s) { 34 | let elevation = 0; 35 | let valleyCount = 0; 36 | 37 | Array.from(s).forEach(step => { 38 | switch (step) { 39 | case 'D': // Downhill 40 | elevation -= 1; 41 | break; 42 | 43 | case 'U': // Uphill 44 | elevation += 1; 45 | 46 | if (elevation === 0) { 47 | valleyCount += 1; 48 | } 49 | 50 | break; 51 | } 52 | }); 53 | 54 | return valleyCount; 55 | } 56 | 57 | function main() { 58 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 59 | const n = parseInt(readLine(), 10); 60 | const s = readLine(); 61 | let result = countingValleys(n, s); 62 | ws.write(result + "\n"); 63 | ws.end(); 64 | } 65 | -------------------------------------------------------------------------------- /ctci-array-left-rotation.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Performs a left rotation on an array. 4 | // 5 | // https://www.hackerrank.com/challenges/ctci-array-left-rotation 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', function() { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function rotLeft(a, d) { 34 | const rotated = a.slice(0, d); 35 | const remainder = a.slice(d); 36 | return remainder.concat(rotated); 37 | } 38 | 39 | function main() { 40 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 41 | const nd = readLine().split(' '); 42 | const n = parseInt(nd[0], 10); 43 | const d = parseInt(nd[1], 10); 44 | const a = readLine().split(' ').map(aTemp => parseInt(aTemp, 10)); 45 | const result = rotLeft(a, d); 46 | ws.write(result.join(' ') + '\n'); 47 | ws.end(); 48 | } 49 | -------------------------------------------------------------------------------- /ctci-bubble-sort.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Performs a bubble sort, counting the number of swaps made. 4 | // 5 | // https://www.hackerrank.com/challenges/ctci-bubble-sort 6 | 7 | 'use strict'; 8 | 9 | process.stdin.resume(); 10 | process.stdin.setEncoding('utf-8'); 11 | 12 | let inputString = ''; 13 | let currentLine = 0; 14 | 15 | process.stdin.on('data', inputStdin => { 16 | inputString += inputStdin; 17 | }); 18 | 19 | process.stdin.on('end', function() { 20 | inputString = inputString.replace(/\s*$/, '') 21 | .split('\n') 22 | .map(str => str.replace(/\s*$/, '')); 23 | 24 | main(); 25 | }); 26 | 27 | function readLine() { 28 | return inputString[currentLine++]; 29 | } 30 | 31 | // Complete the countSwaps function below. 32 | function countSwaps(a) { 33 | let swapCount = 0; 34 | 35 | for (let i = 0; i < a.length; i += 1) { 36 | for (let j = 0; j < a.length - 1; j += 1) { 37 | const numberA = a[j]; 38 | const numberB = a[j + 1]; 39 | 40 | if (numberA > numberB) { 41 | a[j] = numberB; 42 | a[j + 1] = numberA; 43 | swapCount += 1; 44 | } 45 | } 46 | } 47 | 48 | console.log(`Array is sorted in ${swapCount} swaps.`); 49 | console.log('First Element:', a[0]); 50 | console.log('Last Element:', a[a.length - 1]); 51 | } 52 | 53 | function main() { 54 | const n = parseInt(readLine(), 10); 55 | const a = readLine().split(' ').map(aTemp => parseInt(aTemp, 10)); 56 | countSwaps(a); 57 | } 58 | -------------------------------------------------------------------------------- /ctci-ice-cream-parlor.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Finds two values in an array that add up to a given number. 4 | // 5 | // https://www.hackerrank.com/challenges/ctci-ice-cream-parlor 6 | 7 | 'use strict'; 8 | 9 | process.stdin.resume(); 10 | process.stdin.setEncoding('utf-8'); 11 | 12 | let inputString = ''; 13 | let currentLine = 0; 14 | 15 | process.stdin.on('data', inputStdin => { 16 | inputString += inputStdin; 17 | }); 18 | 19 | process.stdin.on('end', function() { 20 | inputString = inputString.replace(/\s*$/, '') 21 | .split('\n') 22 | .map(str => str.replace(/\s*$/, '')); 23 | 24 | main(); 25 | }); 26 | 27 | function readLine() { 28 | return inputString[currentLine++]; 29 | } 30 | 31 | function whatFlavors(cost, money) { 32 | const costMap = cost.reduce((map, value, index) => { 33 | map[value] = index; 34 | return map; 35 | }, {}); 36 | 37 | for (let index = 0; index < cost.length; index += 1) { 38 | const value = cost[index]; 39 | const neededValue = money - value; 40 | const otherIndex = costMap[neededValue]; 41 | 42 | if (otherIndex) { 43 | console.log(index + 1, otherIndex + 1); 44 | return; 45 | } 46 | } 47 | } 48 | 49 | function main() { 50 | const t = parseInt(readLine(), 10); 51 | 52 | for (let tItr = 0; tItr < t; tItr++) { 53 | const money = parseInt(readLine(), 10); 54 | const n = parseInt(readLine(), 10); 55 | const cost = readLine().split(' ').map(costTemp => parseInt(costTemp, 10)); 56 | whatFlavors(cost, money); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /ctci-ransom-note.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Determines whether a message can be created using a given list of words. 4 | // 5 | // https://www.hackerrank.com/challenges/ctci-ransom-note 6 | 7 | 'use strict'; 8 | 9 | process.stdin.resume(); 10 | process.stdin.setEncoding('utf-8'); 11 | 12 | let inputString = ''; 13 | let currentLine = 0; 14 | 15 | process.stdin.on('data', inputStdin => { 16 | inputString += inputStdin; 17 | }); 18 | 19 | process.stdin.on('end', function() { 20 | inputString = inputString.replace(/\s*$/, '') 21 | .split('\n') 22 | .map(str => str.replace(/\s*$/, '')); 23 | 24 | main(); 25 | }); 26 | 27 | function readLine() { 28 | return inputString[currentLine++]; 29 | } 30 | 31 | function checkMagazine(magazine, note) { 32 | const wordMap = magazine.reduce((map, word) => { 33 | map[word] = (map[word] || 0) + 1; 34 | return map; 35 | }, {}); 36 | 37 | for (const word of note) { 38 | if (!wordMap[word]) { 39 | console.log('No'); 40 | return; 41 | } 42 | 43 | wordMap[word] -= 1; 44 | } 45 | 46 | console.log('Yes'); 47 | } 48 | 49 | function main() { 50 | const mn = readLine().split(' '); 51 | const m = parseInt(mn[0], 10); 52 | const n = parseInt(mn[1], 10); 53 | const magazine = readLine().split(' '); 54 | const note = readLine().split(' '); 55 | checkMagazine(magazine, note); 56 | } 57 | -------------------------------------------------------------------------------- /detecting-valid-latitude-and-longitude.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Given a line of text possibly containing latitude and longitude of a point, use 5 | regular expressions to identify latitude and longitude referred to (if any). 6 | 7 | https://www.hackerrank.com/challenges/detecting-valid-latitude-and-longitude 8 | """ 9 | 10 | import re 11 | 12 | 13 | def validate_pairs(pairs): 14 | """Prints 'Valid' for valid lat/lon pairs, 'Invalid' otherwise.""" 15 | pattern = get_pattern() 16 | 17 | for pair in pairs: 18 | print('Valid' if pattern.match(pair) else 'Invalid') 19 | 20 | 21 | def get_pattern(): 22 | """Compiles a regex pattern that matches valid lat/lon pairs.""" 23 | regex = ( 24 | '^\(' # Opening bracket 25 | '[-+]?' # Sign (optional) 26 | '((([1-9]|[1-8]\d)(\.\d+)?)|90(\.0+)?)' # 1 - 90 27 | ', ' 28 | '[-+]?' # Sign (optional) 29 | '((([1-9]\d?|1[0-7]\d)(\.\d+)?)|180(\.0+)?)' # 1 - 180 30 | '\)$' # Closing bracket 31 | ) 32 | 33 | pattern = re.compile(regex) 34 | return pattern 35 | 36 | 37 | if __name__ == '__main__': 38 | pair_count = int(input()) 39 | pairs = (input() for _ in range(pair_count)) 40 | validate_pairs(pairs) 41 | -------------------------------------------------------------------------------- /diagonal-difference.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Calculates absolute difference between the sums of a 2D array's diagonals. 4 | // 5 | // https://www.hackerrank.com/challenges/diagonal-difference 6 | 7 | import Foundation 8 | 9 | let size = Int(readLine()!)! 10 | 11 | let matrix = (1...size).map { _ in 12 | readLine()!.components(separatedBy: " ").flatMap { Int($0) } 13 | } 14 | 15 | let primaryDiagonalSum = (0.. { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.trim().split('\n').map(str => str.trim()); 23 | main(); 24 | }); 25 | 26 | function readLine() { 27 | return inputString[currentLine++]; 28 | } 29 | 30 | function gradingStudents(grades) { 31 | return grades.map(grade => { 32 | if (grade < 38) { 33 | return grade; 34 | } 35 | 36 | const amountBelowNextMultiple = 5 - (grade % 5); 37 | 38 | if (amountBelowNextMultiple < 3) { 39 | grade += amountBelowNextMultiple; 40 | } 41 | 42 | return grade; 43 | }); 44 | } 45 | 46 | function main() { 47 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 48 | const n = parseInt(readLine(), 10); 49 | let grades = []; 50 | 51 | for (let gradesItr = 0; gradesItr < n; gradesItr++) { 52 | const gradesItem = parseInt(readLine(), 10); 53 | grades.push(gradesItem); 54 | } 55 | 56 | let result = gradingStudents(grades); 57 | ws.write(result.join("\n") + "\n"); 58 | ws.end(); 59 | } 60 | -------------------------------------------------------------------------------- /hackerrank-language.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Dtermines if HackerRank API requests contain a valid language. 5 | 6 | https://www.hackerrank.com/challenges/hackerrank-language 7 | """ 8 | 9 | import re 10 | 11 | VALID_LANGUAGES = [ 12 | 'BASH', 'BRAINFUCK', 'C', 'CLISP', 'CLOJURE', 'CPP', 'CSHARP', 'D', 'DART', 13 | 'ERLANG', 'GO', 'GROOVY', 'HASKELL', 'JAVA', 'JAVASCRIPT', 'LUA', 14 | 'OBJECTIVEC', 'OCAML', 'PASCAL', 'PERL', 'PHP', 'PYTHON', 'R', 'RUBY', 15 | 'SCALA', 'SBCL', 16 | ] 17 | 18 | 19 | def verify_request_validity(requests): 20 | """Prints 'VALID' for requests with valid language, 'INVALID' otherwise.""" 21 | pattern = get_pattern() 22 | 23 | for request in requests: 24 | print('VALID' if pattern.match(request) else 'INVALID') 25 | 26 | 27 | def get_pattern(): 28 | """Compiles a regex pattern that matches the valid languages.""" 29 | languages = '|'.join(VALID_LANGUAGES) 30 | regex = '^\d+ ({0})$'.format(languages) 31 | pattern = re.compile(regex) 32 | return pattern 33 | 34 | 35 | if __name__ == '__main__': 36 | request_count = int(input()) 37 | requests = (input() for _ in range(request_count)) 38 | verify_request_validity(requests) 39 | -------------------------------------------------------------------------------- /hackerrank-tweets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Determines how many tweets contain the string 'hackerrank'. 5 | 6 | https://www.hackerrank.com/challenges/hackerrank-tweets 7 | """ 8 | 9 | import re 10 | 11 | 12 | def count_mentions(tweets, keyword): 13 | """Counts the number of tweets that contain the given keyword.""" 14 | pattern = re.compile('^.*hackerrank.*$', re.IGNORECASE) 15 | matching_tweets = [tweet for tweet in tweets if pattern.match(tweet)] 16 | count = len(matching_tweets) 17 | return count 18 | 19 | 20 | if __name__ == '__main__': 21 | tweet_count = int(input()) 22 | tweets = (input() for _ in range(tweet_count)) 23 | print(count_mentions(tweets, 'hackerrank')) 24 | -------------------------------------------------------------------------------- /halloween-party.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Counts the number of times a piece of chocolate can be cut into 1x1 pieces. 5 | 6 | https://www.hackerrank.com/challenges/halloween-party 7 | """ 8 | 9 | 10 | def count_pieces(k): 11 | """Calculates the number of 1x1 pieces that k cuts creates.""" 12 | horizontal_cuts = k // 2 13 | vertical_cuts = k - horizontal_cuts 14 | pieces = horizontal_cuts * vertical_cuts 15 | return pieces 16 | 17 | 18 | if __name__ == '__main__': 19 | test_count = int(input()) 20 | cuts = (int(input()) for _ in range(test_count)) 21 | 22 | for k in cuts: 23 | print(count_pieces(k)) 24 | -------------------------------------------------------------------------------- /ip-address-validation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Detects if lines of text represent an IPv4 address, IPv6 address, or neither. 5 | 6 | https://www.hackerrank.com/challenges/ip-address-validation 7 | """ 8 | 9 | import re 10 | 11 | 12 | def validate_addresses(addresses): 13 | """Identifies the type of IP addresses (IPv4, IPv6, or "Neither").""" 14 | ipv4_pattern = get_ipv4_pattern() 15 | ipv6_pattern = get_ipv6_pattern() 16 | 17 | for address in addresses: 18 | if ipv4_pattern.match(address): 19 | print('IPv4') 20 | elif ipv6_pattern.match(address): 21 | print('IPv6') 22 | else: 23 | print('Neither') 24 | 25 | 26 | def get_ipv4_pattern(): 27 | """Compiles a regex pattern that matches IPv4 addresses.""" 28 | byte = '([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])' # 0 - 255 29 | regex = '^{0}(\.{0}){{3}}$'.format(byte) 30 | pattern = re.compile(regex) 31 | return pattern 32 | 33 | 34 | def get_ipv6_pattern(): 35 | """Compiles a regex pattern that matches IPv6 addresses.""" 36 | hex_group = '[0-9A-Fa-f]{1,4}' # Four hex digits 37 | regex = '^({0})(:{0}){{7}}$'.format(hex_group) 38 | pattern = re.compile(regex) 39 | return pattern 40 | 41 | 42 | if __name__ == '__main__': 43 | address_count = int(input()) 44 | addresses = (input() for _ in range(address_count)) 45 | validate_addresses(addresses) 46 | -------------------------------------------------------------------------------- /japan-population.sql: -------------------------------------------------------------------------------- 1 | -- Finds the total population of Japanese cities. 2 | -- https://www.hackerrank.com/challenges/japan-population 3 | 4 | SELECT SUM(POPULATION) 5 | FROM CITY 6 | WHERE COUNTRYCODE = 'JPN' 7 | -------------------------------------------------------------------------------- /japanese-cities-attributes.sql: -------------------------------------------------------------------------------- 1 | -- Queries all attributes of every Japanese city. 2 | -- https://www.hackerrank.com/challenges/japanese-cities-attributes 3 | 4 | SELECT * 5 | FROM CITY 6 | WHERE COUNTRYCODE = "JPN" 7 | -------------------------------------------------------------------------------- /japanese-cities-name.sql: -------------------------------------------------------------------------------- 1 | -- Query names of all Japanese cities. 2 | -- https://www.hackerrank.com/challenges/japanese-cities-name 3 | 4 | SELECT NAME 5 | FROM CITY 6 | WHERE COUNTRYCODE = "JPN" 7 | -------------------------------------------------------------------------------- /jumping-on-the-clouds.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Counts minimum number of jumps required to traverse array without visiting 1. 4 | // 5 | // https://www.hackerrank.com/challenges/jumping-on-the-clouds 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function jumpingOnClouds(c) { 34 | let jumpCount = 0; 35 | let index = 0; 36 | 37 | while (index < c.length - 1) { 38 | if (c[index + 2] === 0) { 39 | index += 2; 40 | } else { 41 | index += 1; 42 | } 43 | 44 | jumpCount += 1; 45 | } 46 | 47 | return jumpCount; 48 | } 49 | 50 | function main() { 51 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 52 | const n = parseInt(readLine(), 10); 53 | const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10)); 54 | let result = jumpingOnClouds(c); 55 | ws.write(result + "\n"); 56 | ws.end(); 57 | } 58 | -------------------------------------------------------------------------------- /lonely-integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Finds the only number in a list of numbers that isn't a pair. 5 | To do this efficiently we use the property that x ^ x = 0. XORing all numbers 6 | cancels out identical numbers and leaves us with the one we're after. 7 | 8 | https://www.hackerrank.com/challenges/lonely-integer 9 | """ 10 | 11 | from functools import reduce 12 | 13 | 14 | def find_lonely_integer(numbers): 15 | """Finds the number that has no twin.""" 16 | lonely_integer = reduce(lambda x, y: x ^ y, numbers) 17 | return lonely_integer 18 | 19 | 20 | if __name__ == '__main__': 21 | number_count = int(input()) 22 | numbers = (int(x) for x in input().split()) 23 | print(find_lonely_integer(numbers)) 24 | -------------------------------------------------------------------------------- /mark-and-toys.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Determines max number of items that can be purchased within a given budget. 4 | // 5 | // https://www.hackerrank.com/challenges/mark-and-toys 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function maximumToys(prices, k) { 34 | prices.sort((a, b) => a - b); 35 | let numberOfToys = 0; 36 | let total = 0; 37 | 38 | for (let i = 0; i < prices.length; i += 1) { 39 | const price = prices[i]; 40 | 41 | if (total + price > k) { 42 | break; 43 | } 44 | 45 | numberOfToys += 1; 46 | total += price; 47 | } 48 | 49 | return numberOfToys; 50 | } 51 | 52 | function main() { 53 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 54 | const nk = readLine().split(' '); 55 | const n = parseInt(nk[0], 10); 56 | const k = parseInt(nk[1], 10); 57 | const prices = readLine().split(' ').map(pricesTemp => parseInt(pricesTemp, 10)); 58 | let result = maximumToys(prices, k); 59 | ws.write(result + "\n"); 60 | ws.end(); 61 | } 62 | -------------------------------------------------------------------------------- /mini-max-sum.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Finds minimum and maximum values calculated by summing exactly four of five supplied integers. 4 | // 5 | // https://www.hackerrank.com/challenges/mini-max-sum 6 | 7 | import Foundation 8 | 9 | let numbers = readLine()! 10 | .components(separatedBy: " ") 11 | .flatMap { Int($0) } 12 | .sorted() 13 | 14 | let minSum = numbers.prefix(4).reduce(0, +) 15 | let maxSum = numbers.suffix(4).reduce(0, +) 16 | print(minSum, maxSum) 17 | -------------------------------------------------------------------------------- /pairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Given N integers, counts total pairs of integers with a difference of K. 5 | 6 | https://www.hackerrank.com/challenges/pairs 7 | """ 8 | 9 | 10 | def find_pairs_count(numbers, k): 11 | """Finds how many pairs of numbers have a difference of k.""" 12 | answer = 0 13 | distinct = set(numbers) 14 | 15 | for number in numbers: 16 | difference = number - k 17 | 18 | if difference in distinct: 19 | answer += 1 20 | 21 | return answer 22 | 23 | 24 | def numbers_from_input(): 25 | """Reads a list of integers from sdtin.""" 26 | tokens = input().split() 27 | numbers = list(map(int, tokens)) 28 | return numbers 29 | 30 | 31 | if __name__ == '__main__': 32 | n, k = numbers_from_input() 33 | numbers = numbers_from_input() 34 | pairs_count = find_pairs_count(numbers, k) 35 | print(pairs_count) 36 | -------------------------------------------------------------------------------- /plus-minus.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Calculates which fraction of an integer array's elements are positive, negative, and zero. 4 | // 5 | // https://www.hackerrank.com/challenges/plus-minus 6 | 7 | import Foundation 8 | 9 | func fraction(of numbers: [Int], where isIncluded: (Int) -> Bool) -> Double { 10 | let includedNumbers = numbers.filter(isIncluded) 11 | return Double(includedNumbers.count) / Double(numbers.count) 12 | } 13 | 14 | _ = readLine() 15 | let numbers = readLine()!.components(separatedBy: " ").flatMap { Int($0) } 16 | let positive = fraction(of: numbers) { $0 > 0 } 17 | let negative = fraction(of: numbers) { $0 < 0 } 18 | let zero = fraction(of: numbers) { $0 == 0 } 19 | print(positive, negative, zero, separator: "\n") 20 | -------------------------------------------------------------------------------- /population-density-difference.sql: -------------------------------------------------------------------------------- 1 | -- Finds the difference between the maximum and minimum populations. 2 | -- https://www.hackerrank.com/challenges/population-density-difference 3 | 4 | SELECT MAX(POPULATION) - MIN(POPULATION) 5 | FROM CITY 6 | -------------------------------------------------------------------------------- /repeated-string.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Counts the number of occurrences of "a" in an infinitely repeating string. 4 | // 5 | // https://www.hackerrank.com/challenges/repeated-string 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function repeatedString(s, n) { 34 | const aOccurrencesInString = string => Array 35 | .from(string) 36 | .reduce((count, character) => count + (character === 'a' ? 1 : 0), 0); 37 | 38 | const fullyIncludedStringCount = Math.floor(n / s.length); 39 | const remainingCharactersToCheck = n % s.length; 40 | const partialString = s.substring(0, remainingCharactersToCheck) 41 | 42 | return (fullyIncludedStringCount * aOccurrencesInString(s)) + 43 | aOccurrencesInString(partialString); 44 | } 45 | 46 | function main() { 47 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 48 | const s = readLine(); 49 | const n = parseInt(readLine(), 10); 50 | let result = repeatedString(s, n); 51 | ws.write(result + "\n"); 52 | ws.end(); 53 | } 54 | -------------------------------------------------------------------------------- /revising-aggregations-sum.sql: -------------------------------------------------------------------------------- 1 | -- Sums the populations of cities in California. 2 | -- https://www.hackerrank.com/challenges/revising-aggregations-sum 3 | 4 | SELECT SUM(POPULATION) 5 | FROM CITY 6 | WHERE DISTRICT = 'California' 7 | -------------------------------------------------------------------------------- /revising-aggregations-the-average-function.sql: -------------------------------------------------------------------------------- 1 | -- Calculates the average population of cities in California. 2 | -- https://www.hackerrank.com/challenges/revising-aggregations-sum 3 | 4 | SELECT AVG(POPULATION) 5 | FROM CITY 6 | WHERE DISTRICT = 'California' 7 | -------------------------------------------------------------------------------- /revising-aggregations-the-count-function.sql: -------------------------------------------------------------------------------- 1 | -- Counts the number of cities with a population larger than 100,000. 2 | -- https://www.hackerrank.com/challenges/revising-aggregations-the-count-function 3 | 4 | SELECT COUNT(*) 5 | FROM CITY 6 | WHERE POPULATION > 100000 7 | -------------------------------------------------------------------------------- /revising-the-select-query-2.sql: -------------------------------------------------------------------------------- 1 | -- Queries names of all American cities with populations larger than 120000. 2 | -- https://www.hackerrank.com/challenges/revising-the-select-query-2 3 | 4 | SELECT NAME 5 | FROM CITY 6 | WHERE COUNTRYCODE = "USA" AND POPULATION > 120000 7 | -------------------------------------------------------------------------------- /revising-the-select-query.sql: -------------------------------------------------------------------------------- 1 | -- Queries columns for all American cities with populations larger than 100000. 2 | -- https://www.hackerrank.com/challenges/revising-the-select-query 3 | 4 | SELECT * 5 | FROM CITY 6 | WHERE COUNTRYCODE = "USA" AND POPULATION > 100000 7 | -------------------------------------------------------------------------------- /saying-hi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Determines which lines match the pattern 'hi' and aren't immediately 5 | followed by the letter D. Both 'hi' and D are case-insensitive. 6 | 7 | https://www.hackerrank.com/challenges/saying-hi 8 | """ 9 | 10 | import re 11 | 12 | 13 | def print_valid_lines(lines): 14 | """Prints lines that meet the constraints.""" 15 | pattern = re.compile('^hi [^d].*$', re.IGNORECASE) 16 | 17 | for line in lines: 18 | if pattern.match(line): 19 | print(line) 20 | 21 | 22 | if __name__ == '__main__': 23 | line_count = int(input()) 24 | lines = (input() for _ in range(line_count)) 25 | print_valid_lines(lines) 26 | -------------------------------------------------------------------------------- /select-all-sql.sql: -------------------------------------------------------------------------------- 1 | -- Queries all columns for every row. 2 | -- https://www.hackerrank.com/challenges/select-all-sql 3 | 4 | SELECT * 5 | FROM CITY 6 | -------------------------------------------------------------------------------- /select-by-id.sql: -------------------------------------------------------------------------------- 1 | -- Queries all columns for a city with ID 1661. 2 | -- https://www.hackerrank.com/challenges/select-by-id 3 | 4 | SELECT * 5 | FROM CITY 6 | WHERE ID = 1661 7 | -------------------------------------------------------------------------------- /sherlock-and-squares.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Counts the number of square integers (inclusive) between two given numbers. 5 | 6 | https://www.hackerrank.com/challenges/sherlock-and-squares 7 | """ 8 | 9 | import math 10 | 11 | 12 | def squares_between(a, b): 13 | """Finds the number of square integers between a and b.""" 14 | count = math.floor(math.sqrt(b)) - math.floor(math.sqrt(a - 1)) 15 | return count 16 | 17 | 18 | if __name__ == '__main__': 19 | test_count = int(input()) 20 | 21 | for _ in range(test_count): 22 | a, b = tuple(int(pair) for pair in input().split()) 23 | print(squares_between(a, b)) 24 | -------------------------------------------------------------------------------- /simple-array-sum.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Prints the sum of the array's elements as a single integer. 4 | // 5 | // https://www.hackerrank.com/challenges/simple-array-sum 6 | 7 | import Foundation 8 | 9 | _ = readLine() 10 | 11 | let result = readLine()! 12 | .components(separatedBy: " ") 13 | .flatMap { Int($0) } 14 | .reduce(0, +) 15 | 16 | print(result) 17 | -------------------------------------------------------------------------------- /sock-merchant.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Returns an integer representing the number of matching pairs of socks. 4 | // 5 | // https://www.hackerrank.com/challenges/sock-merchant 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function sockMerchant(n, ar) { 34 | const colorCounts = ar.reduce((map, color) => { 35 | map[color] = (map[color] || 0) + 1; 36 | return map; 37 | }, {}); 38 | 39 | return Object 40 | .values(colorCounts) 41 | .reduce((pairCount, colorCount) => pairCount + Math.floor(colorCount / 2), 0); 42 | } 43 | 44 | function main() { 45 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 46 | const n = parseInt(readLine(), 10); 47 | const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10)); 48 | let result = sockMerchant(n, ar); 49 | ws.write(result + "\n"); 50 | ws.end(); 51 | } 52 | -------------------------------------------------------------------------------- /solve-me-first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Introductory challenge. 5 | 6 | https://www.hackerrank.com/challenges/solve-me-first 7 | """ 8 | 9 | 10 | if __name__ == '__main__': 11 | a = int(input()) 12 | b = int(input()) 13 | print(a + b) 14 | -------------------------------------------------------------------------------- /split-number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Splits phone numbers into their country code, local area code, and number. 5 | 6 | https://www.hackerrank.com/challenges/split-number 7 | """ 8 | 9 | import re 10 | 11 | 12 | def split_phone_numbers(numbers): 13 | """Prints the separated groups of phone numbers.""" 14 | pattern = get_pattern() 15 | 16 | for number in numbers: 17 | match = pattern.match(number) 18 | output = ('CountryCode={country_code},' 19 | 'LocalAreaCode={area_code},' 20 | 'Number={number}').format(**match.groupdict()) 21 | print(output) 22 | 23 | 24 | def get_pattern(): 25 | """Compiles a regex pattern that groups phone number parts.""" 26 | regex = ( 27 | '(?P\d{1,3})' 28 | '[ -]' 29 | '(?P\d{1,3})' 30 | '[ -]' 31 | '(?P\d{4,10})' 32 | ) 33 | 34 | pattern = re.compile(regex) 35 | return pattern 36 | 37 | 38 | if __name__ == '__main__': 39 | number_count = int(input()) 40 | numbers = (input() for _ in range(number_count)) 41 | split_phone_numbers(numbers) 42 | -------------------------------------------------------------------------------- /staircase.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env xcrun swift 2 | 3 | // Prints a staircase of the supplied size. 4 | // 5 | // https://www.hackerrank.com/challenges/compare-the-triplets 6 | 7 | import Foundation 8 | 9 | let stairCount = Int(readLine()!)! 10 | 11 | (1...stairCount) 12 | .map { stair in 13 | let characters = String(repeating: "#", count: stair) 14 | .padding(toLength: stairCount, withPad: " ", startingAt: 0) 15 | .characters 16 | .reversed() 17 | 18 | return String(characters) 19 | } 20 | .forEach { print($0) } 21 | -------------------------------------------------------------------------------- /the-love-letter-mystery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Counts the number of operations required to convert a word to a palindrome. 5 | 6 | https://www.hackerrank.com/challenges/the-love-letter-mystery 7 | """ 8 | 9 | from itertools import islice 10 | 11 | 12 | def count_operations(word): 13 | """Determines operations needed to convert word -> palindrome.""" 14 | difference = lambda x, y: abs(ord(x) - ord(y)) 15 | median = len(word) // 2 16 | pairs = zip(word, reversed(word)) 17 | operations = sum(difference(x, y) for x, y in islice(pairs, median)) 18 | return operations 19 | 20 | 21 | if __name__ == '__main__': 22 | word_count = int(input()) 23 | 24 | for _ in range(word_count): 25 | word = input() 26 | print(count_operations(word)) 27 | -------------------------------------------------------------------------------- /time-conversion.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Converts a 12-hour AM/PM format to military (24-hour) time. 4 | // 5 | // https://www.hackerrank.com/challenges/time-conversion 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.trim().split('\n').map(str => str.trim()); 23 | main(); 24 | }); 25 | 26 | function readLine() { 27 | return inputString[currentLine++]; 28 | } 29 | 30 | function timeConversion(s) { 31 | const regex = /(\d{2}):(\d{2}):(\d{2})(\w{2})/g; 32 | let [, hours, minutes, seconds, period] = regex.exec(s); 33 | 34 | if (period === 'AM' && hours === '12') { 35 | hours = '00'; 36 | } else if (period === 'PM' && hours !== '12') { 37 | hours = (parseInt(hours) + 12).toString(); 38 | } 39 | 40 | return `${hours}:${minutes}:${seconds}`; 41 | } 42 | 43 | function main() { 44 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 45 | const s = readLine(); 46 | let result = timeConversion(s); 47 | ws.write(result + "\n"); 48 | ws.end(); 49 | } 50 | -------------------------------------------------------------------------------- /two-strings.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Determines whether two strings share a common substring. 4 | // 5 | // https://www.hackerrank.com/challenges/two-strings 6 | 7 | 'use strict'; 8 | 9 | const fs = require('fs'); 10 | 11 | process.stdin.resume(); 12 | process.stdin.setEncoding('utf-8'); 13 | 14 | let inputString = ''; 15 | let currentLine = 0; 16 | 17 | process.stdin.on('data', inputStdin => { 18 | inputString += inputStdin; 19 | }); 20 | 21 | process.stdin.on('end', _ => { 22 | inputString = inputString.replace(/\s*$/, '') 23 | .split('\n') 24 | .map(str => str.replace(/\s*$/, '')); 25 | 26 | main(); 27 | }); 28 | 29 | function readLine() { 30 | return inputString[currentLine++]; 31 | } 32 | 33 | function twoStrings(s1, s2) { 34 | const s1Set = new Set(s1); 35 | const s2Set = new Set(s2); 36 | return Array.from(s1Set).some(character => s2Set.has(character)) ? 'YES' : 'NO'; 37 | } 38 | 39 | function main() { 40 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 41 | const q = parseInt(readLine(), 10); 42 | 43 | for (let qItr = 0; qItr < q; qItr++) { 44 | const s1 = readLine(); 45 | const s2 = readLine(); 46 | let result = twoStrings(s1, s2); 47 | ws.write(result + "\n"); 48 | } 49 | 50 | ws.end(); 51 | } 52 | -------------------------------------------------------------------------------- /uk-and-us-2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Counts the occurrences of words in their British and American spelling. 5 | Specifically, given a word containing the UK "our", also count occurences of 6 | words with the US "or" (e.g. treat colour and color the same). 7 | 8 | https://www.hackerrank.com/challenges/uk-and-us-2 9 | """ 10 | 11 | import re 12 | 13 | 14 | def count_occurrences(lines, words): 15 | """Counts occurrences of words with US and UK spelling in given lines.""" 16 | for word in words: 17 | pattern = get_pattern(word) 18 | count = sum(len(pattern.findall(line)) for line in lines) 19 | print(count) 20 | 21 | 22 | def get_pattern(word): 23 | """Compiles a regex pattern that matches the US and UK word spelling.""" 24 | word_regex = word.replace('our', 'ou?r') 25 | # Ensure word isn't substring of another / followed by other letters. 26 | # That is, we don't want a match for "savour" with the word "savoury". 27 | regex = '{0}(?!\w)'.format(word_regex) 28 | pattern = re.compile(regex) 29 | return pattern 30 | 31 | 32 | if __name__ == '__main__': 33 | line_count = int(input()) 34 | lines = [input() for _ in range(line_count)] 35 | word_count = int(input()) 36 | words = (input() for _ in range(word_count)) 37 | count_occurrences(lines, words) 38 | -------------------------------------------------------------------------------- /uk-and-us.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Counts the occurrences of words in their British and American spelling. 5 | Specifically, given a word with the US "ze" suffix, also count occurrences of 6 | words with the UK "se" suffix (e.g. treat realize and realise the same). 7 | 8 | https://www.hackerrank.com/challenges/uk-and-us 9 | """ 10 | 11 | import re 12 | 13 | 14 | def count_occurrences(lines, words): 15 | """Counts occurrences of words with US and UK spelling in given lines.""" 16 | for word in words: 17 | pattern = get_pattern(word) 18 | count = sum(len(pattern.findall(line)) for line in lines) 19 | print(count) 20 | 21 | 22 | def get_pattern(word): 23 | """Compiles a regex pattern that matches the US and UK word spelling.""" 24 | regex = '{0}[sz]e'.format(word[:-2]) 25 | pattern = re.compile(regex) 26 | return pattern 27 | 28 | 29 | if __name__ == '__main__': 30 | line_count = int(input()) 31 | lines = [input() for _ in range(line_count)] 32 | word_count = int(input()) 33 | words = (input() for _ in range(word_count)) 34 | count_occurrences(lines, words) 35 | -------------------------------------------------------------------------------- /utopian-identification-number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Identifies whether fictional identification numbers are valid. 5 | 6 | https://www.hackerrank.com/challenges/utopian-identification-number 7 | """ 8 | 9 | import re 10 | 11 | 12 | def validate_ids(ids): 13 | """Prints 'VALID' for valid IDs, 'INVALID' otherwise.""" 14 | pattern = re.compile('^[a-z]{,3}\d{2,8}[A-Z]{3,}$') 15 | 16 | for citizen_id in ids: 17 | print('VALID' if pattern.match(citizen_id) else 'INVALID') 18 | 19 | 20 | if __name__ == '__main__': 21 | id_count = int(input()) 22 | ids = (input() for _ in range(id_count)) 23 | validate_ids(ids) 24 | -------------------------------------------------------------------------------- /utopian-tree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Finds the height of a "Utopian tree" after some number of growth cycles. 5 | 6 | https://www.hackerrank.com/challenges/utopian-tree 7 | """ 8 | 9 | from itertools import cycle, islice 10 | 11 | 12 | def calculate_height(cycle_count): 13 | """Determines the height of a tree given number of cycles that passed.""" 14 | growths = cycle([lambda x: x * 2, lambda x: x + 1]) 15 | height = 1 16 | 17 | for growth in islice(growths, cycle_count): 18 | height = growth(height) 19 | 20 | return height 21 | 22 | 23 | if __name__ == '__main__': 24 | tree_count = int(input()) 25 | 26 | for _ in range(tree_count): 27 | cycle_count = int(input()) 28 | print(calculate_height(cycle_count)) 29 | -------------------------------------------------------------------------------- /valid-pan-format.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Identifies whether PAN numbers are valid. 5 | 6 | https://www.hackerrank.com/challenges/valid-pan-format 7 | """ 8 | 9 | import re 10 | 11 | 12 | def validate_pan_numbers(numbers): 13 | """Prints 'YES' for valid IDs, 'NO' otherwise.""" 14 | pattern = re.compile('^[A-Z]{5}\d{4}[A-Z]$') 15 | 16 | for number in numbers: 17 | print('YES' if pattern.match(number) else 'NO') 18 | 19 | 20 | if __name__ == '__main__': 21 | number_count = int(input()) 22 | numbers = (input() for _ in range(number_count)) 23 | validate_pan_numbers(numbers) 24 | -------------------------------------------------------------------------------- /weather-observation-station-1.sql: -------------------------------------------------------------------------------- 1 | -- Queries a list of cities and states. 2 | -- https://www.hackerrank.com/challenges/weather-observation-station-1 3 | 4 | SELECT CITY, STATE 5 | FROM STATION 6 | -------------------------------------------------------------------------------- /weather-observation-station-2.sql: -------------------------------------------------------------------------------- 1 | -- Calculates the sum of the latitude and longitude. 2 | -- https://www.hackerrank.com/challenges/weather-observation-station-2 3 | 4 | SELECT ROUND(SUM(LAT_N), 2), ROUND(SUM(LONG_W), 2) 5 | FROM STATION 6 | -------------------------------------------------------------------------------- /weather-observation-station-3.sql: -------------------------------------------------------------------------------- 1 | -- Queries a list of city names with even IDs. 2 | -- https://www.hackerrank.com/challenges/weather-observation-station-3 3 | 4 | SELECT DISTINCT CITY 5 | FROM STATION 6 | WHERE ID % 2 = 0 7 | -------------------------------------------------------------------------------- /weather-observation-station-4.sql: -------------------------------------------------------------------------------- 1 | -- Finds the difference between total entries and distinct ones. 2 | -- https://www.hackerrank.com/challenges/weather-observation-station-4 3 | 4 | SELECT COUNT(CITY) - COUNT(DISTINCT CITY) 5 | FROM STATION 6 | --------------------------------------------------------------------------------