text
stringlengths 2
104M
| meta
dict |
---|---|
add_hackerrank(longest-increasing-subsequent longest-increasing-subsequent.cpp)
dirty_cpp(longest-increasing-subsequent)
add_hackerrank(dorsey-thief dorsey-thief.cpp)
add_hackerrank_py(fibonacci-modified.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// The Longest Increasing Subsequence
// Find the length of the longest increase subsequence in a given array.
//
// https://www.hackerrank.com/challenges/longest-increasing-subsequent/problem
//
#include <bits/stdc++.h>
using namespace std;
// C++ implementation to find longest increasing subsequence
// in O(n Log n) time.
// Binary search
int GetCeilIndex(int arr[], vector<int> &T, int l, int r,
int key)
{
while (r - l > 1)
{
int m = l + (r - l)/2;
if (arr[T[m]] >= key)
r = m;
else
l = m;
}
return r;
}
int LongestIncreasingSubsequence(int arr[], int n)
{
// Add boundary case, when array n is zero
// Depend on smart pointers
vector<int> tailIndices(n, 0); // Initialized with 0
vector<int> prevIndices(n, -1); // initialized with -1
int len = 1; // it will always point to empty location
for (int i = 1; i < n; i++)
{
if (arr[i] < arr[tailIndices[0]])
{
// new smallest value
tailIndices[0] = i;
}
else if (arr[i] > arr[tailIndices[len - 1]])
{
// arr[i] wants to extend largest subsequence
prevIndices[i] = tailIndices[len - 1];
tailIndices[len++] = i;
}
else
{
// arr[i] wants to be a potential condidate of
// future subsequence
// It will replace ceil value in tailIndices
int pos = GetCeilIndex(arr, tailIndices, -1,
len - 1, arr[i]);
prevIndices[i] = tailIndices[pos - 1];
tailIndices[pos] = i;
}
}
return len;
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for(int arr_i = 0; arr_i < n; arr_i++){
cin >> arr[arr_i];
}
int result = LongestIncreasingSubsequence(&arr.at(0), arr.size() );
cout << result << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Dynamic Programming](https://www.hackerrank.com/domains/algorithms/dynamic-programming)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Fibonacci Modified](https://www.hackerrank.com/challenges/fibonacci-modified)|Compute the nth term of a Fibonacci sequence.|[Python](fibonacci-modified.py)|Medium
[The Longest Increasing Subsequence](https://www.hackerrank.com/challenges/longest-increasing-subsequent)|Find the length of the longest increase subsequence in a given array.|[C++](longest-increasing-subsequent.cpp)|Advanced
[Dorsey Thief](https://www.hackerrank.com/challenges/dorsey-thief)|standard knapsack problem|[C++](dorsey-thief.cpp)|Advanced
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Making Anagrams
# How many characters should one delete to make two given strings anagrams of each other?
#
# https://www.hackerrank.com/challenges/making-anagrams/problem
#
def makingAnagrams(s1, s2):
# Complete this function
a = [0] * 26
b = [0] * 26
for c in s1:
j = ord(c) - ord('a')
a[j] += 1
for c in s2:
j = ord(c) - ord('a')
b[j] += 1
return sum(abs(a[i] - b[i]) for i in range(26))
s1 = input().strip()
s2 = input().strip()
result = makingAnagrams(s1, s2)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Pangrams
# Check whether a given string is a panagram or not.
#
# https://www.hackerrank.com/challenges/pangrams/problem
#
def pangrams(s):
# si le set() a 26 éléments, on y a stocké les 26 lettres de l'alphabet
letters = set()
for c in s:
c = c.lower()
if c.isalpha(): letters.add(c)
if len(letters) == 26:
print("pangram")
else:
print("not pangram")
if __name__ == '__main__':
s = input()
pangrams(s)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Palindrome Index
# Determine which character(s) must be removed to make a string a palindrome.
#
# https://www.hackerrank.com/challenges/palindrome-index/problem
#
import sys
def est_palindrome(s):
return s == s[::-1]
def palindromeIndex(s):
# Complete this function
n = len(s)
i = 0
j = n - 1
while i < j:
if s[i] != s[j]:
if s[i + 1] == s[j]:
if est_palindrome(s[:i] +s[i + 1:]):
return i
if s[i] == s[j - 1]:
if est_palindrome(s[:j] + s[j + 1:]):
return j
i += 1
j -= 1
return -1
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = palindromeIndex(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Weighted Uniform Strings
# Determine if a string contains uniform substrings of certain weights.
#
# https://www.hackerrank.com/challenges/weighted-uniform-string/problem
#
def weightedUniformStrings(s, queries):
weights = set()
prev = ''
w = 0
for c in s:
if prev != c:
prev = c
w = 0
w += (ord(c) - ord('a') + 1)
weights.add(w)
for q in queries:
if q in weights:
print("Yes")
else:
print("No")
if __name__ == '__main__':
s = input()
queries_count = int(input())
queries = []
for _ in range(queries_count):
queries_item = int(input())
queries.append(queries_item)
weightedUniformStrings(s, queries)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Anagram
# Find the minimum number of characters of the first string that we need to change in order to make it an anagram of the second string.
#
# https://www.hackerrank.com/challenges/anagram/problem
#
def anagram(s):
n = len(s)
if n % 2 == 1: return -1
a = [0] * 26
b = [0] * 26
for i in range(n // 2):
j = ord(s[i]) - ord('a')
a[j] += 1
for i in range(n // 2, n):
j = ord(s[i]) - ord('a')
b[j] += 1
return sum(abs(a[i] - b[i]) for i in range(26)) // 2
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = anagram(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Gemstones
# Find the number of different gem-elements present.
#
# https://www.hackerrank.com/challenges/gem-stones/problem
#
# les minéraux de chaque pierre
minerals = [set(input()) for _ in range(int(input()))]
# minéraux présents dans toutes les pierres
minerals = set.intersection(*minerals)
# le résultat...
print(len(minerals))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Common Child
// Given two strings a and b of equal length, what's the longest string (s) that can be constructed such that s is a child to both a and b?
//
// https://www.hackerrank.com/challenges/common-child/problem
//
// ref: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
#include <bits/stdc++.h>
size_t lcs_length(const std::string& s1, const std::string& s2)
{
size_t m = s1.size();
size_t n = s2.size();
std::vector<size_t> C((m + 1) * (n + 1), 0);
size_t K = n + 1;
for (size_t i = 0; i < m; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (s1[i] == s2[j])
C[i + 1 + (j + 1) * K] = C[i + j * K] + 1;
else
C[i + 1 + (j + 1) * K] = std::max(C[(i + 1) + j * K], C[i + (j + 1) * K]);
}
}
return C[m + n * K];
}
int main()
{
std::string s1;
std::string s2;
std::cin >> s1 >> s2;
std::cout << lcs_length(s1, s2) << std::endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# CamelCase
#
#
# https://www.hackerrank.com/challenges/camelcase/problem
#
import sys
def camelcase(s):
# Complete this function
# +1 pour le premier mot, après il suffit de compter les majuscules
return 1 + sum(1 for c in s if c.upper() == c)
if __name__ == "__main__":
s = input().strip()
result = camelcase(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# String Construction
# Find the minimum cost of copying string s.
#
# https://www.hackerrank.com/challenges/string-construction/problem
#
# aucun intérêt: la réponse est: le nombre de caractères différents!
def stringConstruction(s):
return len(set(s))
if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = stringConstruction(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Separate the Numbers
# Determine if a numeric string can be broken into a sequence of increasing numbers.
#
# https://www.hackerrank.com/challenges/separate-the-numbers/problem
#
import sys
# cas un peu complexe, il faut bien gérer ses compteurs
def separateNumbers(s):
# Complete this function
for i in range(1, len(s) // 2 + 1):
j = i
k = 0
prev = -1
ugly = False
# print("test", i,file=sys.stderr)
while k + j <= len(s):
# règle n°2
if s[k] == "0" and j > 1:
ugly = True
break
n = int(s[k:k + j])
# print("prev=",prev,"n=",n,"j=",j,file=sys.stderr)
if prev != -1:
if n != prev + 1:
j += 1
n = int(s[k:k + j])
# règle n°1
if n != prev + 1:
ugly = True
break
prev = n
k += j
if not ugly and k == len(s):
# print("k=",k,"j=",j,"len(s)=",len(s),file=sys.stderr)
print("YES", s[0:i])
return
print("NO")
if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
s = input().strip()
separateNumbers(s)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Common Child
# Given two strings a and b of equal length, what's the longest string (s) that can be constructed such that s is a child to both a and b?
#
# https://www.hackerrank.com/challenges/common-child/problem
#
# https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
# à exécuter avec PyPy3, sinon trop lent
def lcs_length(s1, s2):
m = len(s1)
n = len(s2)
C = [0] * (m + 1) * (n + 1)
K = n + 1
for i in range(m):
for j in range(n):
if s1[i] == s2[j]:
C[i + 1 + (j + 1) * K] = C[i + j * K] + 1
else:
C[i + 1 + (j + 1) * K] = max(C[(i + 1) + j * K], C[i + (j + 1) * K])
return C[m + n * K]
s1 = input().strip()
s2 = input().strip()
result = lcs_length(s1, s2)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# HackerRank in a String!
# Determine if a string contains a subsequence of characters that spell "hackerrank".
#
# https://www.hackerrank.com/challenges/hackerrank-in-a-string/problem
#
def hackerrankInString(s):
# Complete this function
p = "hackerrank"
i = 0
for c in s:
if c == p[i]:
i += 1
if i == len(p):
return "YES"
return "NO"
if __name__ == "__main__":
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = hackerrankInString(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Sherlock and the Valid String
# Remove some characters from the string such that the new string's characters have the same frequency.
#
# https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem
#
#!/bin/python3
import sys
def isValid(s):
# Complete this function
f = [0] * 26
for c in s:
f[ord(c) - ord('a')] += 1
a = b = max(f)
for i in f:
if i > 0 and i < a:
a = i
# la fréquence est la même
if a == b: return "YES"
if a == 1:
# une lettre isolée, le reste est sur la même fréquence
if sum(1 for i in f if i == a) == 1: return "YES"
if b - a > 1: return "NO"
if sum(1 for i in f if i == b) == 1: return "YES"
if sum(1 for i in f if i == a) > 1: return "NO"
return "YES"
s = input().strip()
result = isValid(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Alternating Characters
# Calculate the minimum number of deletions required to convert a string into a string in which consecutive characters are different.
#
# https://www.hackerrank.com/challenges/alternating-characters/problem
#
import itertools
def alternatingCharacters(s):
return sum(len(list(g)) - 1 for k, g in itertools.groupby(s))
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = alternatingCharacters(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Strings > Two Characters
# Print the length of the longest possible string $t$ you can form.
#
# https://www.hackerrank.com/challenges/two-characters/problem
#
import sys
import re
import itertools
_, s = input(), input()
result = 0
for pair in itertools.combinations("abcdefghijklmnopqrstuvwxyz", 2):
t = ''.join(c for c in s if c in pair)
if not re.search(r'(.)\1', t) and len(t) >= 2:
print(pair, t, file=sys.stderr)
result = max(result, len(t))
print(result) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Mars Exploration
# Save Our Ship!
#
# https://www.hackerrank.com/challenges/mars-exploration/problem
#
def marsExploration(s):
# Complete this function
nb = 0
i = 0
while i < len(s):
c = s[i]
if c != "SOS"[i % 3]:
nb += 1
i += 1
return nb
if __name__ == "__main__":
s = input().strip()
result = marsExploration(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(sherlock-and-valid-string.py)
add_hackerrank_py(making-anagrams.py)
add_hackerrank_py(game-of-thrones.py)
add_hackerrank_py(reduced-string.py)
add_hackerrank_py(the-love-letter-mystery.py)
add_hackerrank_py(beautiful-binary-string.py)
add_hackerrank_py(funny-string.py)
add_hackerrank_py(alternating-characters.py)
add_hackerrank_py(gem-stones.py)
add_hackerrank_py(palindrome-index.py)
#add_hackerrank_py(common-child.py)
add_hackerrank_py(string-construction.py)
add_hackerrank_py(anagram.py)
add_hackerrank_py(mars-exploration.py)
add_hackerrank_py(weighted-uniform-string.py)
add_hackerrank_py(determining-dna-health.py)
add_hackerrank_py(sherlock-and-anagrams.py)
add_hackerrank_py(two-strings.py)
add_hackerrank_py(caesar-cipher-1.py)
add_hackerrank(morgan-and-a-string morgan-and-a-string.c)
add_hackerrank(common-child common-child.cpp)
add_hackerrank_py(richie-rich.py)
add_hackerrank_py(camelcase.py)
add_hackerrank_py(pangrams.py)
add_hackerrank_py(separate-the-numbers.py)
add_hackerrank_py(hackerrank-in-a-string.py)
add_hackerrank_py(strong-password.py)
add_hackerrank_py(two-characters.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Sherlock and Anagrams
# Find the number of unordered anagramic pairs of substrings of a string.
#
# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
#
import sys
def sherlockAndAnagrams(s):
ana = { }
nb = 0
n = len(s)
for i in range(0, n):
for j in range(i + 1, n + 1):
a = ''.join(sorted(s[i:j]))
if a in ana:
ana[a] += 1
nb += ana[a]
else:
ana[a] = 0
return nb
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = sherlockAndAnagrams(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Morgan and a String
// Find the lexicographically minimal string that can be formed by the combination of two strings.
//
// https://www.hackerrank.com/challenges/morgan-and-a-string/problem
//
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
char *morgan;
void morganAndString(const char *a, const char *b) {
// Complete this function
char *r = morgan;
while (*a && *b)
{
if (strcmp(a, b) < 0)
{
*r++ = *a++;
if (!*a) { strcpy(r, b); return; }
}
else
{
*r++ = *b++;
if (!*b) { strcpy(r, a); return; }
}
}
*r = 0;
}
int main() {
int t;
char *a, *b;
a = (char *)malloc(128000 * sizeof(char));
b = (char *)malloc(128000 * sizeof(char));
morgan = (char *)malloc(256000 * sizeof(char));
scanf("%i", &t);
for(int a0 = 0; a0 < t; a0++) {
scanf("%s", a);
scanf("%s", b);
strcat(a, "z");
strcat(b, "z");
morganAndString(a, b);
morgan[strlen(a) + strlen(b)-2] = 0;
printf("%s\n", morgan);
}
free(a);
free(b);
free(morgan);
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Super Reduced String
# Given a string, repeatedly remove adjacent pairs of matching characters and then print the reduced result.
#
# https://www.hackerrank.com/challenges/reduced-string/problem
#
def super_reduced_string(s):
# Complete this function
l = len(s)
i = 0
r = ""
while i < l - 1:
if s[i] == s[i + 1]:
i += 2
else:
if len(r) != 0 and r[-1] == s[i]:
r = r[:-1]
else:
r += s[i]
i += 1
if i == l - 1:
if len(r) != 0 and r[-1] == s[l - 1]:
r = r[:-1]
else:
r += s[l - 1]
if r == "":
r = "Empty String"
return r
s = input().strip()
result = super_reduced_string(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Funny String
# Is the absolute difference between consecutive characters is the same for a string and the reverse of that string for all indices.
#
# https://www.hackerrank.com/challenges/funny-string/problem
#
def funnyString(s):
# nota: le demi-parcours suffit, sinon on teste 2 fois la même chose
for i in range(0, len(s) // 2):
if abs(ord(s[i]) - ord(s[i + 1])) != abs(ord(s[-1 - i]) - ord(s[-2 - i])):
print("Not Funny")
return
print("Funny")
q = int(input())
for _ in range(q):
s = input()
funnyString(s)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Beautiful Binary String
# How many binary characters must you change to remove every occurrence of "010" from a binary string?
#
# https://www.hackerrank.com/challenges/beautiful-binary-string/problem
#
# deux opérations suffisent à enlever le motif 010
# 01010 -> 01110
# 010 -> 000
# pour dénombrer, il suffit donc de compter le nombre d'occurences de 010 qui ne se recouvrent pas
def beautifulBinaryString(b):
n = 0
while True:
p = b.find('01010')
if p == -1: break
b = b[:p + 2] + '1' + b[p + 3:]
n += 1
while True:
p = b.find('010')
if p == -1: break
b = b[:p + 1] + '0' + b[p + 2:]
n += 1
return n
if __name__ == "__main__":
n = int(input().strip())
b = input().strip()
result = beautifulBinaryString(b)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Caesar Cipher
# Encrypt a string by rotating the alphabets by a fixed value in the string.
#
# https://www.hackerrank.com/challenges/caesar-cipher-1/problem
#
def caesarCipher(s, k):
# Complete this function
def caesar():
for c in s:
c = ord(c)
if 97 <= c <= 122:
c = 97 + ((c - 97) + k) % 26
elif 65 <= c <= 90:
c = 65 + ((c - 65) + k) % 26
yield chr(c)
return ''.join(caesar())
if __name__ == "__main__":
n = int(input().strip())
s = input().strip()
k = int(input().strip())
result = caesarCipher(s, k)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Game of Thrones - I
# Check whether any anagram of a string can be a palindrome or not.
#
# https://www.hackerrank.com/challenges/game-of-thrones/problem
#
# il faut une seule lettre en nombre impair si len(s) est impaire
# sinon toutes les lettres doivent être en nombre pair
def gameOfThrones(s):
# Complete this function
a = [0] * 26
for c in s:
a[ord(c) - ord('a')] += 1
b = [0] * 2
for i in a:
b[i % 2] += 1
return "YES" if b[1] <= len(s) % 2 else "NO"
s = input().strip()
result = gameOfThrones(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Two Strings
# Given two strings, you find a common substring of non-zero length.
#
# https://www.hackerrank.com/challenges/two-strings/problem
#
def twoStrings(s1, s2):
# Complete this function
return "YES" if len(set.intersection(set(s1), set(s2))) > 0 else "NO"
q = int(input().strip())
for a0 in range(q):
s1 = input().strip()
s2 = input().strip()
result = twoStrings(s1, s2)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# The Love-Letter Mystery
# Find the minimum number of operations required to convert a given string into a palindrome under certain conditions
#
# https://www.hackerrank.com/challenges/the-love-letter-mystery/problem
#
def theLoveLetterMystery(s):
return sum(abs(ord(s[i]) - ord(s[-i - 1])) for i in range(len(s) // 2))
q = int(input())
for a0 in range(q):
s = input()
result = theLoveLetterMystery(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Strings > Strong Password
# How many characters should you add to make the password strong?
#
# https://www.hackerrank.com/challenges/strong-password/problem
#
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"
# pseudo strpbrk()
def strpbrk(s1, s2):
for c in s2:
if s1.find(c) != -1: return True
return False
def minimumNumber(n, password):
# Return the minimum number of characters to make the password strong
k = 0
if not strpbrk(password, numbers): k += 1
if not strpbrk(password, lower_case): k += 1
if not strpbrk(password, upper_case): k += 1
if not strpbrk(password, special_characters): k += 1
while n + k < 6: k += 1
return k
if __name__ == "__main__":
n = int(input().strip())
password = input().strip()
answer = minimumNumber(n, password)
print(answer)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Strings](https://www.hackerrank.com/domains/algorithms/strings)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Super Reduced String](https://www.hackerrank.com/challenges/reduced-string)|Given a string, repeatedly remove adjacent pairs of matching characters and then print the reduced result.|[Python](reduced-string.py)|Easy
[CamelCase](https://www.hackerrank.com/challenges/camelcase)||[Python](camelcase.py)|Easy
[Strong Password](https://www.hackerrank.com/challenges/strong-password)|How many characters should you add to make the password strong?|[Python](strong-password.py)|Easy
[Two Characters](https://www.hackerrank.com/challenges/two-characters)|Print the length of the longest possible string $t$ you can form.|[Python](two-characters.py)|Easy
[Caesar Cipher](https://www.hackerrank.com/challenges/caesar-cipher-1)|Encrypt a string by rotating the alphabets by a fixed value in the string.|[Python](caesar-cipher-1.py)|Easy
[Mars Exploration](https://www.hackerrank.com/challenges/mars-exploration)|Save Our Ship!|[Python](mars-exploration.py)|Easy
[HackerRank in a String!](https://www.hackerrank.com/challenges/hackerrank-in-a-string)|Determine if a string contains a subsequence of characters that spell "hackerrank".|[Python](hackerrank-in-a-string.py)|Easy
[Pangrams](https://www.hackerrank.com/challenges/pangrams)|Check whether a given string is a panagram or not.|[Python](pangrams.py)|Easy
[Weighted Uniform Strings](https://www.hackerrank.com/challenges/weighted-uniform-string)|Determine if a string contains uniform substrings of certain weights.|[Python](weighted-uniform-string.py)|Easy
[Separate the Numbers](https://www.hackerrank.com/challenges/separate-the-numbers)|Determine if a numeric string can be broken into a sequence of increasing numbers.|[Python](separate-the-numbers.py)|Easy
[Funny String](https://www.hackerrank.com/challenges/funny-string)|Is the absolute difference between consecutive characters is the same for a string and the reverse of that string for all indices.|[Python](funny-string.py)|Easy
[Gemstones](https://www.hackerrank.com/challenges/gem-stones)|Find the number of different gem-elements present.|[Python](gem-stones.py)|Easy
[Alternating Characters ](https://www.hackerrank.com/challenges/alternating-characters)|Calculate the minimum number of deletions required to convert a string into a string in which consecutive characters are different.|[Python](alternating-characters.py)|Easy
[Beautiful Binary String](https://www.hackerrank.com/challenges/beautiful-binary-string)|How many binary characters must you change to remove every occurrence of "010" from a binary string?|[Python](beautiful-binary-string.py)|Easy
[The Love-Letter Mystery](https://www.hackerrank.com/challenges/the-love-letter-mystery)|Find the minimum number of operations required to convert a given string into a palindrome under certain conditions|[Python](the-love-letter-mystery.py)|Easy
[Determining DNA Health](https://www.hackerrank.com/challenges/determining-dna-health)|Determine which weighted substrings in a subset of substrings can be found in a given string and calculate the string's total weight.|[Python](determining-dna-health.py)|Hard
[Palindrome Index](https://www.hackerrank.com/challenges/palindrome-index)|Determine which character(s) must be removed to make a string a palindrome.|[Python](palindrome-index.py)|Easy
[Anagram](https://www.hackerrank.com/challenges/anagram)|Find the minimum number of characters of the first string that we need to change in order to make it an anagram of the second string.|[Python](anagram.py)|Easy
[Making Anagrams](https://www.hackerrank.com/challenges/making-anagrams)|How many characters should one delete to make two given strings anagrams of each other?|[Python](making-anagrams.py)|Easy
[Game of Thrones - I](https://www.hackerrank.com/challenges/game-of-thrones)|Check whether any anagram of a string can be a palindrome or not.|[Python](game-of-thrones.py)|Easy
[Two Strings](https://www.hackerrank.com/challenges/two-strings)|Given two strings, you find a common substring of non-zero length.|[Python](two-strings.py)|Easy
[String Construction ](https://www.hackerrank.com/challenges/string-construction)|Find the minimum cost of copying string s.|[Python](string-construction.py)|Easy
[Sherlock and the Valid String](https://www.hackerrank.com/challenges/sherlock-and-valid-string)|Remove some characters from the string such that the new string's characters have the same frequency.|[Python](sherlock-and-valid-string.py)|Medium
[Highest Value Palindrome](https://www.hackerrank.com/challenges/richie-rich)|Make a number palindromic in no more than $k$ moves, maximal.|[Python](richie-rich.py)|Medium
[Sherlock and Anagrams](https://www.hackerrank.com/challenges/sherlock-and-anagrams)|Find the number of unordered anagramic pairs of substrings of a string.|[Python](sherlock-and-anagrams.py)|Medium
[Common Child](https://www.hackerrank.com/challenges/common-child)|Given two strings a and b of equal length, what's the longest string (s) that can be constructed such that s is a child to both a and b?|[C++](common-child.cpp) [Python](common-child.py)|Medium
[Morgan and a String](https://www.hackerrank.com/challenges/morgan-and-a-string)|Find the lexicographically minimal string that can be formed by the combination of two strings.|[C](morgan-and-a-string.c)|Expert
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Determining DNA Health
# Determine which weighted substrings in a subset of substrings can be found in a given string and calculate the string's total weight.
#
# https://www.hackerrank.com/challenges/determining-dna-health/problem
#
class KMP:
""" Knuth-Morris-Pratt """
def __init__(self, pattern):
""" Calculate partial match table: String -> [Int]"""
self.partial = ret = [0]
self.pattern = pattern
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] == pattern[i] else j)
def search(self, T, overlapping=False):
"""
KMP search main algorithm: String -> String -> [Int]
Return all the matching position of pattern string P in S
"""
partial, ret, j = self.partial, [], 0
P = self.pattern
for i in range(len(T)):
while j > 0 and T[i] != P[j]:
j = partial[j - 1]
if T[i] == P[j]: j += 1
if j == len(P):
ret.append(i - (j - 1))
if overlapping:
j = partial[j - 1]
else:
j = 0
return ret
unhealthiest, healthiest = 10 ** 7, 0
n = input()
genes = [KMP(gene) for gene in input().split()]
health = list(map(int, input().split()))
for _ in range(int(input())):
first, last, d = input().split()
first, last, d = [int(first), int(last), str(d)]
h = 0
for i in range(first, last + 1):
p = genes[i].search(d, True)
h += health[i] * len(p)
unhealthiest = min(unhealthiest, h)
healthiest = max(healthiest, h)
print(unhealthiest, healthiest)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Highest Value Palindrome
# Make a number palindromic in no more than $k$ moves, maximal.
#
# https://www.hackerrank.com/challenges/richie-rich/problem
#
#!/bin/python3
import os
import sys
#
# Complete the highestValuePalindrome function below.
#
def highestValuePalindrome(s, n, k):
pos = []
p = []
for i in range(0, n // 2):
if s[i] != s[-1 - i]:
if k == 0: return "-1"
k -= 1
# on retient le chiffre le plus grand
p += max(s[i], s[-1 - i])
# on mémorise la position du changement
# pour passer à 9 éventuellement plus tard
pos.append(i)
else:
p += s[i]
# autant que possible maximise le résultat en mettant des 9
# i.e. autant qu'on a des crédits k
i = 0
while k > 0 and i < len(p):
if p[i] != '9':
if i in pos:
# si c'était un chiffre déjà changé, le coût est 1 au lieu de 2
p[i] = '9'
k -= 1
elif k >= 2:
p[i] = '9'
k -= 2
i += 1
# ajoute le caractère du milieu isolé si nombre impair
if n % 2 == 1:
if k >= 1:
# il reste un crédit: on maximise
p += '9'
else:
p += s[n // 2]
# ajoute le p inversé pour faire le palindrome
if n % 2 == 1:
p = p + p[-2::-1]
else:
p = p + p[::-1]
return ''.join(p)
if __name__ == '__main__':
n, k = map(int, input().split())
s = input()
result = highestValuePalindrome(s, n, k)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Ice Cream Parlor
# Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor.
#
# https://www.hackerrank.com/challenges/icecream-parlor/problem
#
def icecreamParlor(money, arr):
# Complete this function
m = {}
for i, a in enumerate(arr, 1):
r = money - a
if r in m:
print(m[r], i)
return
m[a] = i
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
m = int(input().strip())
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
icecreamParlor(m, arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Search > Sherlock and Array
# Check whether there exists an element in the array such that sum of elements on its left is equal to the sum of elements on its right.
#
# https://www.hackerrank.com/challenges/sherlock-and-array/problem
# https://www.hackerrank.com/contests/101may14/challenges/sherlock-and-array
# challenge id: 2490
#
def solve(a):
i = 0
j = len(a) - 1
l = r = 0
while i < j:
if l < r:
l += a[i]
i += 1
else:
r += a[j]
j -= 1
return "YES" if l == r else "NO"
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
result = solve(a)
print(result) | {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Search > Missing Numbers
# Find the numbers missing from a sequence given a permutation of the original sequence
#
# https://www.hackerrank.com/challenges/missing-numbers/problem
#
# définit un tableau pour compter les nombres
# 200 comme ça pas la peine de chercher le min: on centre sur la première valeur rencontrée
arr = [0] * 200
offset = None
input() # skip n
for i in map(int, input().split()):
if offset is None:
offset = i - 100
arr[i - offset] += 1
input() # skip m
for i in map(int, input().split()):
arr[i - offset] -= 1
print(" ".join(str(k + offset) for k, i in enumerate(arr) if i != 0))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Search > Hackerland Radio Transmitters
# Find the minimum number of radio transmitters needed to cover all the houses in Hackerland!
#
# https://www.hackerrank.com/challenges/hackerland-radio-transmitters/problem
#
def hackerlandRadioTransmitters(n, x, k):
x = sorted(x)
nb = 0
i = 0
while i < n:
# essaie de placer l'émetteur le plus loin possible vers la droite
portee = x[i] + k # on cherche vers la droite le point qui couvre i
while i < n and x[i] <= portee: i += 1
i -= 1
# on place l'émetteur sur le point i
nb += 1
# saute les points couverts à droite
portee = x[i] + k # on saute tous les points couverts par l'émetteur en ri
while i < n and x[i] <= portee: i += 1
return nb
if __name__ == "__main__":
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
x = list(map(int, input().strip().split(' ')))
result = hackerlandRadioTransmitters(n, x, k)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(pairs.py)
add_hackerrank_py(icecream-parlor.py)
add_hackerrank_py(missing-numbers.py)
add_hackerrank_py(hackerland-radio-transmitters.py)
add_hackerrank_py(sherlock-and-array.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
"""
Pairs
https://www.hackerrank.com/challenges/pairs/problem
"""
import sys
import bisect
def pairs(k, arr):
# Complete this function
arr = sorted(arr)
nb = 0
length = len(arr)
for v in arr:
i = bisect.bisect_left(arr, v + k)
while i < length and arr[i] == v + k:
i += 1
nb += 1
return nb
if __name__ == "__main__":
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
arr = list(map(int, input().strip().split(' ')))
result = pairs(k, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Search](https://www.hackerrank.com/domains/algorithms/search)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Hackerland Radio Transmitters](https://www.hackerrank.com/challenges/hackerland-radio-transmitters)|Find the minimum number of radio transmitters needed to cover all the houses in Hackerland!|[Python](hackerland-radio-transmitters.py)|Medium
[Ice Cream Parlor](https://www.hackerrank.com/challenges/icecream-parlor)|Help Sunny and Johnny spend all their money during each trip to the Ice Cream Parlor.|[Python](icecream-parlor.py)|Easy
[Missing Numbers](https://www.hackerrank.com/challenges/missing-numbers)|Find the numbers missing from a sequence given a permutation of the original sequence|[Python](missing-numbers.py)|Easy
[Pairs](https://www.hackerrank.com/challenges/pairs)|Given N numbers, count the total pairs of numbers that have a difference of K.|[Python](pairs.py)|Medium
[Sherlock and Array](https://www.hackerrank.com/challenges/sherlock-and-array)|Check whether there exists an element in the array such that sum of elements on its left is equal to the sum of elements on its right.|[Python](sherlock-and-array.py)|Easy
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Bit Manipulation > The Great XOR
// Count the number of non-negative integer a's that are less than some x where the bitwise XOR of a and x is greater than x.
//
// https://www.hackerrank.com/challenges/the-great-xor/problem
// https://www.hackerrank.com/contests/w28/challenges/the-great-xor
// challenge id: 27667
//
#include <bits/stdc++.h>
using namespace std;
// Complete the theGreatXor function below.
long theGreatXor(long x) {
long r = 0;
long mask = 1;
while (mask < x)
{
if ((mask & x) == 0)
r += mask;
mask <<= 1;
}
return r;
}
int main()
{
int q;
cin >> q;
while (q--)
{
long x;
cin >> x;
cout << theGreatXor(x) << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Hamming Distance
// You are given a string S, consisting of N small latin letters 'a'
// and 'b'. Process the given M queries.
//
// https://www.hackerrank.com/challenges/hamming-distance/problem
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
std::string str1, str2;
size_t n, m;
char cmd;
cin >> n;
cin >> str1;
cin >> m;
str2.resize(n);
char *buf[2] =
{
const_cast<char *>(str1.data()),
const_cast<char *>(str2.data()),
};
int cur = 0;
char *s = buf[0];
while (m-- != 0)
{
cin >> cmd;
if (cmd == 'C')
{
size_t l, r;
char ch;
cin >> l >> r >> ch;
for (size_t i = l - 1; i < r; ++i) s[i] = ch;
}
else if (cmd == 'R')
{
size_t l, r;
cin >> l >> r;
for (size_t i = 0; i < (r - l + 1) / 2; ++i)
swap(s[i + l - 1], s[r - i - 1]);
}
else if (cmd == 'W')
{
size_t l, r;
cin >> l >> r;
cout.write(s + l - 1, (streamsize)(r - l + 1));
cout << endl;
}
else if (cmd == 'H')
{
size_t l1, l2, len;
cin >> l1 >> l2 >> len;
int h = 0;
l1--;
l2--;
for (size_t i = 0; i < len; ++i)
{
if (s[l1 + i] != s[l2 + i]) h++;
}
cout << h << endl;
}
else if (cmd == 'S')
{
size_t l1, r1, l2, r2;
cin >> l1 >> r1 >> l2 >> r2;
char *tmp = buf[1 - cur];
#define COPY(a, b) if (b != 0) { memcpy(tmp, s + a, b); tmp += b; }
COPY(0, l1 - 1);
COPY(l2 - 1, r2 - l2 + 1);
COPY(r1, l2 - r1 - 1);
COPY(l1 - 1, r1 - l1 + 1);
COPY(r2, n - r2);
cur = 1 - cur;
s = buf[cur];
}
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Bit Manipulation > A or B
# A or B = C
#
# https://www.hackerrank.com/challenges/aorb/problem
#
def aOrB16(a, b, c):
n = 0
i = 0
na, nb = 0, 0
for i in range(16):
a, ra = divmod(a, 2)
b, rb = divmod(b, 2)
c, rc = divmod(c, 2)
if rc == 0:
# il faut changer les 1 en 0 dans a et/ou b
n += ra + rb
else:
# si 0 dans a et b, il faut mettre 1 dans l'un ou l'autre
n += 1 - (ra | rb)
if (ra | rb) == 0: rb = 1
na |= ra << i
nb |= rb << i
return na, nb, n
def precompute():
d = [0] * 4096
for a in range(16):
for b in range(16):
for c in range(16):
d[a * 256 + b * 16 + c] = aOrB16(a, b, c)
return d
# https://oeis.org/A000120
# nombre de 1 dans l'écriture binaire de n ou "Hamming weight"
nb_bits = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
aOrB_table = precompute()
def aOrB(k, a, b, c):
la = len(a)
lb = len(b)
lc = len(c)
maxlen = max(la, lb, lc)
a = [0] * (maxlen - la) + list(int(i, 16) for i in a)
b = [0] * (maxlen - lb) + list(int(i, 16) for i in b)
c = [0] * (maxlen - lc) + list(int(i, 16) for i in c)
n = k
for i in range(maxlen):
ra, rb, rn = aOrB_table[a[i] * 256 + b[i] * 16 + c[i]]
n -= rn
if n < 0:
print(-1)
return
a[i] = ra
b[i] = rb
if n > 0:
# on peut encore annuler n bits entre A' et B'
# (ceux qui valent 1 dans les 2 nombres, en commençant par A')
for i in range(maxlen):
if a[i] == 0: continue
for j in range(3, -1, -1):
if n >= 2 and a[i] & (1 << j) != 0 and b[i] & (1 << j) == 0:
# on peut faire passer 1 bit de A' vers B'
a[i] &= 15 - (1 << j)
b[i] |= (1 << j)
n -= 2
elif a[i] & b[i] & (1 << j) != 0:
# on peut annuler 1 bit de A'
a[i] &= 15 - (1 << j)
n -= 1
if n == 0: break
if n == 0: break
def to_hex(a):
i = 0
while i < maxlen - 1 and a[i] == 0:
i += 1
while i < maxlen:
yield "0123456789ABCDEF"[a[i]]
i += 1
print(''.join(to_hex(a)))
print(''.join(to_hex(b)))
if __name__ == '__main__':
q = int(input())
for _ in range(q):
k = int(input())
a = input().strip()
b = input().strip()
c = input().strip()
aOrB(k, a, b, c)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(lonely-integer.py)
add_hackerrank(hamming-distance hamming-distance.cpp)
add_hackerrank_py(maximizing-xor.py)
add_hackerrank_py(aorb.py)
add_hackerrank_py(counter-game.py)
add_hackerrank(flipping-bits flipping-bits.cpp)
add_hackerrank(the-great-xor the-great-xor.cpp)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Bit Manipulation > Counter game
# Louise and Richard play a game, find the winner of the game.
#
# https://www.hackerrank.com/challenges/counter-game/problem
#
pow2 = [1 << i for i in range(63, -1, -1)]
def counterGame(n):
player = 0
while n != 1:
# print( ["Louise", "Richard"][player],n)
for i in pow2:
if n == i:
n = n // 2
if n != 1:
player = 1 - player
break
elif n & i == i:
n = n - i
if n != 1:
player = 1 - player
break
return ["Louise", "Richard"][player]
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
result = counterGame(n)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Lonely Integer
# Find the unique element in an array of integer pairs.
#
# https://www.hackerrank.com/challenges/lonely-integer/problem
#
import functools
import operator
def lonelyinteger(a):
# Complete this function
# fonctionne car les nombres sont en double sauf un :
# le xor va annuler les nombres en double (i xor i = 0)
# et il ne restera que l'unique (i xor 0 = i)
return functools.reduce(operator.xor, a)
# solution plus triviale, mais fonctionne si les nombres
# sont en triple, quadruple, etc.
one = set()
two_or_more = set()
for i in a:
if i in one:
two_or_more.add(i)
else:
one.add(i)
return (one - two_or_more).pop()
n = int(input())
a = list(map(int, input().split()))
result = lonelyinteger(a)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Bit Manipulation > Flipping bits
// Flip bits in its binary representation.
//
// https://www.hackerrank.com/challenges/flipping-bits/problem
// https://www.hackerrank.com/contests/101hack20/challenges/flipping-bits
// challenge id: 5529
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
uint32_t a;
cin >> a;
cout << ~a << endl;
}
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Bit Manipulation > Maximizing XOR
# Given two integers, L and R, find the maximal value of A xor B,
# where A and B satisfy a condition.
#
# https://www.hackerrank.com/challenges/maximizing-xor/problem
#
# L = 00000101......
# R = 00000111......
# L^R = 00000010......
# sol = 0000001111...1 on met des 1 après le bit le plus à gauche de L^R
def maximizingXor(l, r):
# Complete this function
r = l ^ r
m = 0
while r != 0:
r //= 2
m = m * 2 + 1
return m
if __name__ == "__main__":
l = int(input().strip())
r = int(input().strip())
result = maximizingXor(l, r)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Bit Manipulation](https://www.hackerrank.com/domains/algorithms/bit-manipulation)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Lonely Integer](https://www.hackerrank.com/challenges/lonely-integer)|Find the unique element in an array of integer pairs.|[Python](lonely-integer.py)|Easy
[Maximizing XOR](https://www.hackerrank.com/challenges/maximizing-xor)|Given two integers, L and R, find the maximal value of A xor B, where A and B satisfy a condition.|[Python](maximizing-xor.py)|Easy
[Counter game](https://www.hackerrank.com/challenges/counter-game)|Louise and Richard play a game, find the winner of the game.|[Python](counter-game.py)|Medium
[The Great XOR](https://www.hackerrank.com/challenges/the-great-xor)|Count the number of non-negative integer a's that are less than some x where the bitwise XOR of a and x is greater than x.|[C++](the-great-xor.cpp)|Medium
[Flipping bits](https://www.hackerrank.com/challenges/flipping-bits)|Flip bits in its binary representation.|[C++](flipping-bits.cpp)|Easy
[A or B](https://www.hackerrank.com/challenges/aorb)|A or B = C|[Python](aorb.py)|Medium
[Hamming Distance](https://www.hackerrank.com/challenges/hamming-distance)|You are given a string S, consisting of N small latin letters 'a' and 'b'. Process the given M queries.|[C++](hamming-distance.cpp)|Expert
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(new-year-chaos.py)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Constructive Algorithms > New Year Chaos
# Determine how many bribes took place to get a queue into its current state.
#
# https://www.hackerrank.com/challenges/new-year-chaos/problem
# https://www.hackerrank.com/contests/hourrank-4/challenges/new-year-chaos
# challenge id: 15305
#
import math
import os
import random
import re
import sys
# Complete the minimumBribes function below.
def minimumBribes(q):
q.insert(0, 0)
length = len(q)
for i, v in enumerate(q):
if v - i > 2:
print("Too chaotic")
return
swaps = 0
for i in range(length - 1):
before = swaps
for j in range(length - 1):
if q[j] > q[j + 1]:
q[j], q[j + 1] = q[j + 1], q[j]
swaps += 1
swaped = True
if swaps == before:
break
print(swaps)
return
# minimal swaps:
ref = [0] * (length)
for i, x in enumerate(q):
ref[x] = i
swaps = 0
for i in range(length):
k = q[i]
if k != i:
q[i], q[ref[i]] = q[ref[i]], q[i]
ref[i], ref[k] = ref[k], ref[i]
swaps += 1
print(swaps)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
q = list(map(int, input().split()))
minimumBribes(q)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Constructive Algorithms](https://www.hackerrank.com/domains/algorithms/constructive-algorithms)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[New Year Chaos](https://www.hackerrank.com/challenges/new-year-chaos)|Determine how many bribes took place to get a queue into its current state.|[Python](new-year-chaos.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Debugging > Prime Dates
// Find the number of prime dates in a range
//
// https://www.hackerrank.com/challenges/prime-date/problem
// challenge id: 63495
//
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Main {
public static int month[];
public static void main (String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
month = new int[15];
String s = in.nextLine();
StringTokenizer str = new StringTokenizer(s, "- ");
int d1 = Integer.parseInt(str.nextToken());
int m1 = Integer.parseInt(str.nextToken());
int y1 = Integer.parseInt(str.nextToken());
int d2 = Integer.parseInt(str.nextToken());
int m2 = Integer.parseInt(str.nextToken());
int y2 = Integer.parseInt(str.nextToken());
int result = findPrimeDates(d1, m1, y1, d2, m2, y2);
System.out.println(result);
}
public static void updateLeapYear(int year) {
if(year % 400 == 0) {
month[2] = 29; // <== CORRIGER ICI
} else if(year % 100 == 0) {
month[2] = 28;
} else if(year % 4 == 0) {
month[2] = 29; // <== CORRIGER ICI
} else {
month[2] = 28;
}
}
public static void storeMonth() {
month[1] = 31;
month[2] = 28;
month[3] = 31;
month[4] = 30;
month[5] = 31;
month[6] = 30;
month[7] = 31;
month[8] = 31;
month[9] = 30;
month[10] = 31;
month[11] = 30;
month[12] = 31;
}
public static int findPrimeDates(int d1, int m1, int y1, int d2, int m2, int y2) {
storeMonth();
int result = 0;
while(true) {
int x = d1;
x = x * 100 + m1;
x = x * 10000 + y1; // <== CORRIGER ICI
if(x % 4 == 0 || x % 7 == 0) { // <== CORRIGER ICI
result = result + 1;
}
if(d1 == d2 && m1 == m2 && y1 == y2) {
break;
}
updateLeapYear(y1);
d1 = d1 + 1;
if(d1 > month[m1]) {
m1 = m1 + 1;
d1 = 1;
if(m1 > 12) {
y1 = y1 + 1;
m1 = 1; // <== CORRIGER ICI
}
}
}
return result;
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Debugging > Prime Dates
# Find the number of prime dates in a range
#
# https://www.hackerrank.com/challenges/prime-date/problem
# challenge id: 63495
#
import re
month = []
def updateLeapYear(year):
if year % 400 == 0:
month[2] = 29
elif year % 100 == 0:
month[2] = 28
elif year % 4 == 0:
month[2] = 29
else:
month[2] = 28
def storeMonth():
month[1] = 31
month[2] = 28
month[3] = 31
month[4] = 30
month[5] = 31
month[6] = 30
month[7] = 31
month[8] = 31
month[9] = 30
month[10] = 31
month[11] = 30
month[12] = 31
def findPrimeDates(d1, m1, y1, d2, m2, y2):
storeMonth()
result = 0
while(True):
x = d1
x = x * 100 + m1
x = x * 10000 + y1
if x % 4 == 0 or x % 7 == 0:
result = result + 1
if d1 == d2 and m1 == m2 and y1 == y2:
break
updateLeapYear(y1)
d1 = d1 + 1
if d1 > month[m1]:
m1 = m1 + 1
d1 = 1
if m1 > 12:
y1 = y1 + 1
m1 = 1
return result;
for i in range(1, 15):
month.append(31)
line = input()
date = re.split('-| ', line)
d1 = int(date[0])
m1 = int(date[1])
y1 = int(date[2])
d2 = int(date[3])
m2 = int(date[4])
y2 = int(date[5])
result = findPrimeDates(d1, m1, y1, d2, m2, y2)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Algorithms > Debugging > Zig Zag Sequence
# Find a zig zag sequence of the given array.
#
# https://www.hackerrank.com/challenges/zig-zag-sequence/problem
# challenge id: 63282
#
def findZigZagSequence(a, n):
a.sort()
mid = int((n - 1)/2)
a[mid], a[n-1] = a[n-1], a[mid]
st = mid + 1
ed = n - 2
while(st <= ed):
a[st], a[ed] = a[ed], a[st]
st = st + 1
ed = ed - 1
for i in range (n):
if i == n-1:
print(a[i])
else:
print(a[i], end = ' ')
return
test_cases = int(input())
for cs in range (test_cases):
n = int(input())
a = list(map(int, input().split()))
findZigZagSequence(a, n)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Debugging > Zig Zag Sequence
// Find a zig zag sequence of the given array.
//
// https://www.hackerrank.com/challenges/zig-zag-sequence/problem
// challenge id: 63282
//
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main (String[] args) throws java.lang.Exception {
Scanner kb = new Scanner(System.in);
int test_cases = kb.nextInt();
for(int cs = 1; cs <= test_cases; cs++){
int n = kb.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; i++){
a[i] = kb.nextInt();
}
findZigZagSequence(a, n);
}
}
public static void findZigZagSequence(int [] a, int n){
Arrays.sort(a);
int mid = (n - 1)/2; // <== CORRIGER ICI
int temp = a[mid];
a[mid] = a[n - 1];
a[n - 1] = temp;
int st = mid + 1;
int ed = n - 2; // <== CORRIGER ICI
while(st <= ed){
temp = a[st];
a[st] = a[ed];
a[ed] = temp;
st = st + 1;
ed = ed - 1; // <== CORRIGER ICI
}
for(int i = 0; i < n; i++){
if(i > 0) System.out.print(" ");
System.out.print(a[i]);
}
System.out.println();
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank(prime-date prime-date.cpp)
add_hackerrank_py(prime-date.py)
add_hackerrank_java(prime-date.java CLASS Main)
add_hackerrank(zig-zag-sequence zig-zag-sequence.cpp)
add_hackerrank_py(zig-zag-sequence.py)
add_hackerrank_java(zig-zag-sequence.java CLASS Main)
dirty_cpp(prime-date)
dirty_cpp(zig-zag-sequence)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Debugging > Zig Zag Sequence
// Find a zig zag sequence of the given array.
//
// https://www.hackerrank.com/challenges/zig-zag-sequence/problem
// challenge id: 63282
//
#include <bits/stdc++.h>
using namespace std;
void findZigZagSequence(vector < int > a, int n){
sort(a.begin(), a.end());
int mid = (n - 1)/2;
swap(a[mid], a[n-1]);
int st = mid + 1;
int ed = n - 2;
while(st <= ed){
swap(a[st], a[ed]);
st = st + 1;
ed = ed - 1;
}
for(int i = 0; i < n; i++){
if(i > 0) cout << " ";
cout << a[i];
}
cout << endl;
}
int main() {
int n, x;
int test_cases;
cin >> test_cases;
for(int cs = 1; cs <= test_cases; cs++){
cin >> n;
vector < int > a;
for(int i = 0; i < n; i++){
cin >> x;
a.push_back(x);
}
findZigZagSequence(a, n);
}
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Algorithms > Debugging > Prime Dates
// Find the number of prime dates in a range
//
// https://www.hackerrank.com/challenges/prime-date/problem
// challenge id: 63495
//
#include <bits/stdc++.h>
using namespace std;
int month[15];
void updateLeapYear(int year) {
if(year % 400 == 0) {
month[2] = 29;
} else if(year % 100 == 0) {
month[2] = 28;
} else if(year % 4 == 0) {
month[2] = 29;
} else {
month[2] = 28;
}
}
void storeMonth() {
month[1] = 31;
month[2] = 28;
month[3] = 31;
month[4] = 30;
month[5] = 31;
month[6] = 30;
month[7] = 31;
month[8] = 31;
month[9] = 30;
month[10] = 31;
month[11] = 30;
month[12] = 31;
}
int findLuckyDates(int d1, int m1, int y1, int d2, int m2, int y2) {
storeMonth();
int result = 0;
while(true) {
int x = d1;
x = x * 100 + m1;
x = x * 10000 + y1;
if(x % 4 == 0 || x % 7 == 0) {
result = result + 1;
}
if(d1 == d2 && m1 == m2 && y1 == y2) {
break;
}
updateLeapYear(y1);
d1 = d1 + 1;
if(d1 > month[m1]) {
m1 = m1 + 1;
d1 = 1;
if(m1 > 12) {
y1 = y1 + 1;
m1 = 1;
}
}
}
return result;
}
int main() {
string str;
int d1, m1, y1, d2, m2, y2;
getline(cin, str);
for(int i = 0; i < str.size(); i++) {
if(str[i] == '-') {
str[i] = ' ';
}
}
stringstream ss;
ss << str;
ss >> d1 >> m1 >> y1 >> d2 >> m2 >> y2;
int result = findLuckyDates(d1, m1, y1, d2, m2, y2);
cout << result << endl;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
### [Algorithms](https://www.hackerrank.com/domains/algorithms)
The true test of problem solving: when one realizes that time and memory aren't infinite.
#### [Debugging](https://www.hackerrank.com/domains/algorithms/algo-debugging)
Name | Preview | Code | Difficulty
---- | ------- | ---- | ----------
[Prime Dates](https://www.hackerrank.com/challenges/prime-date)|Find the number of prime dates in a range|[C++](prime-date.cpp) [Java](prime-date.java) [Python](prime-date.py)|Medium
[Zig Zag Sequence](https://www.hackerrank.com/challenges/zig-zag-sequence)|Find a zig zag sequence of the given array.|[C++](zig-zag-sequence.cpp) [Java](zig-zag-sequence.java) [Python](zig-zag-sequence.py)|Medium
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Utopian Tree
# Predict the height of the tree after N growth cycles.
#
# https://www.hackerrank.com/challenges/utopian-tree/problem
#
def utopianTree(n):
# Complete this function
H = 1
for i in range(n):
if i % 2 == 0:
H *= 2
else:
H += 1
return H
if __name__ == "__main__":
t = int(input())
for a0 in range(t):
n = int(input())
result = utopianTree(n)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Halloween Sale
# How many games can you buy during the Halloween Sale?
#
# https://www.hackerrank.com/challenges/halloween-sale/problem
#
def howManyGames(p, d, m, s):
# Return the number of games you can buy
# p = prix d'origine
# d = ristourne
# m = prix minimum
# s = budget
# plutôt que de trouver la formule exacte, on peut se contenter de boucler
# il y a 10^4 itérations au max
nb = 0
while s >= p:
s -= p
p = max(m, p - d)
nb += 1
return nb
if __name__ == "__main__":
p, d, m, s = input().strip().split(' ')
p, d, m, s = [int(p), int(d), int(m), int(s)]
answer = howManyGames(p, d, m, s)
print(answer)
""" ici la solution mathématique:
from math import floor, sqrt
p, d, m, s = map(int, input().split())
x = ((p-m) + (d-1)) // d # after x games, all cost m
cx = x*p - ((x*(x-1))>>1)*d
if s <= cx:
# solve (-d/2)*n^2 + (p-d/2)*n - s <= 0
v = 1 + p/d
print(floor(v - sqrt(v*v - 2*s/d)))
else:
print(x + (s - cx) // m)
"""
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Divisible Sum Pairs
# Count the number of pairs in an array having sums that are evenly divisible by a given number.
#
# https://www.hackerrank.com/challenges/divisible-sum-pairs/problem
#
def divisibleSumPairs(n, k, ar):
# Complete this function
nb = 0
for i in range(0, n - 1):
for j in range(i + 1, n):
if (ar[i] + ar[j]) % k == 0:
nb += 1
return nb
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
ar = list(map(int, input().strip().split(' ')))
result = divisibleSumPairs(n, k, ar)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Manasa and Stones
# Calculate the possible values of the last stone where consecutive values on the stones differ by a value 'a' or a value 'b'.
#
# https://www.hackerrank.com/challenges/manasa-and-stones/problem
#
def stones(n, a, b):
# si a==b une seule valeur possible
if a == b:
return [(n - 1) * a]
r = []
if a > b: a, b = b, a
# sinon c'est l'ensemble de a+a+a+...+b+b (n termes)
for i in range(n):
r.append(a * (n - 1 - i) + b * i)
return r
if __name__ == "__main__":
T = int(input().strip())
for a0 in range(T):
n = int(input().strip())
a = int(input().strip())
b = int(input().strip())
result = stones(n, a, b)
print (" ".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Encryption
# Encrypt a string by arranging the characters of a string into a matrix and printing the resulting matrix column wise.
#
# https://www.hackerrank.com/challenges/encryption/problem
#
import math
def encryption(s):
# Complete this function
s = s.replace(' ', '')
L = math.sqrt(len(s))
row = math.floor(L)
col = row
if row * col < len(s): col += 1
# prend un caractère tous les col, en partant du i-ème
return " ".join(s[i::col] for i in range(col))
if __name__ == "__main__":
s = input().strip()
result = encryption(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# The Time in Words
# Display the time in words.
#
# https://www.hackerrank.com/challenges/the-time-in-words/problem
#
numbers = ["", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen", "twenty"]
def timeInWords(h, m):
# Complete this function
if m == 0:
return "{} o' clock".format(numbers[h])
if m > 30:
verb = "to"
h += 1
if h == 13:
h = 1
m = 60 - m
else:
verb = "past"
if m == 1:
return "one minute {} {}".format(verb, numbers[h])
if m == 30:
return "half past {}".format(numbers[h])
if m == 15:
return "quarter {} {}".format(verb, numbers[h])
if m > 20:
return "{} {} minutes {} {}".format(numbers[20], numbers[m - 20], verb, numbers[h])
return "{} minutes {} {}".format(numbers[m], verb, numbers[h])
if __name__ == "__main__":
h = int(input().strip())
m = int(input().strip())
result = timeInWords(h, m)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Breaking the Records
# Given an array of Maria's basketball scores all season, determine the number of times she breaks her best and worst records.
#
# https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
#
def breakingRecords(score):
# Complete this function
nmin, nmax = 0, 0
smin, smax = score[0], score[0]
for s in score[1:]:
if s < smin:
smin = s
nmin += 1
if s > smax:
smax = s
nmax += 1
return nmax, nmin
if __name__ == "__main__":
n = int(input().strip())
score = list(map(int, input().strip().split(' ')))
result = breakingRecords(score)
print (" ".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Beautiful Days at the Movies
# Find the number of beautiful days.
#
# https://www.hackerrank.com/challenges/beautiful-days-at-the-movies/problem
#
def beautifulDays(i, j, k):
# Complete this function
return sum(1 for n in range(i, j + 1)
if abs(n - int(''.join(reversed(str(n))))) % k == 0)
if __name__ == "__main__":
i, j, k = input().strip().split(' ')
i, j, k = [int(i), int(j), int(k)]
result = beautifulDays(i, j, k)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# The Grid Search
# Given a 2D array of digits, try to find a given 2D grid pattern of digits within it.
#
# https://www.hackerrank.com/challenges/the-grid-search/problem
#
def gridSearch(G, P):
# on cherche dans toute les lignes de G
i = 0
while i <= len(G) - len(P):
p0 = 0
while True:
j = 0
i0 = i
# cherche si P[0] se trouve dans la ligne courante de G
p = G[i0].find(P[j], p0)
if p == -1:
break
# cherche le reste de P, à la même position
# (OK pas optimisé, mais plus clair à écrire!)
while j < len(P) and i0 < len(G) and p == G[i0].find(P[j], p0):
i0 += 1
j += 1
if j == len(P):
return "YES"
# le motif P[0] peut se retrouver plus loin dans la ligne...
p0 = p + 1
i += 1
return "NO"
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
R, C = input().strip().split(' ')
R, C = [int(R), int(C)]
G = []
G_i = 0
for G_i in range(R):
G_t = str(input().strip())
G.append(G_t)
r, c = input().strip().split(' ')
r, c = [int(r), int(c)]
P = []
P_i = 0
for P_i in range(r):
P_t = str(input().strip())
P.append(P_t)
result = gridSearch(G, P)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Append and Delete
# Can you convert $s$ to $t$ by performing exactly $k$ operations?
#
# https://www.hackerrank.com/challenges/append-and-delete/problem
#
import sys
def appendAndDelete(s, t, k):
# Complete this function
if k >= len(s) + len(t): return "Yes"
i = 0
while i < min(len(s), len(t)) and s[i] == t[i]:
i += 1
k -= len(s) - i # pour supprimer les caractères de fin différents
k -= len(t) - i # pour ajouter les caractères de fin
if k < 0: return "No"
if k == 0: return "Yes"
if k % 2 == 0: return "Yes"
if k > len(s) * 2: return "Yes"
return "No"
if __name__ == "__main__":
s = input()
t = input()
k = int(input())
print(appendAndDelete(s, t, k))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Non-Divisible Subset
# Find the size of the maximal non-divisible subset.
#
# https://www.hackerrank.com/challenges/non-divisible-subset/problem
#
def nonDivisibleSubset(k, arr):
# algorithme:
# - pour que Ai + Aj soit divisibe par k, il faut que :
# Ai % k + Aj % k = k
# - on compte les nombres Ai qui ont le même reste de la division par k
# restes[r] = nombre de Ai tel que Ai % k == r
# - pour un reste donné r, il faudra éliminer les nombres du groupe r
# ou les nombres du groupe k-r : on gardera les plus nombreux
# - cas particulier de r == 0:
# ce sont les diviseurs de k. S'il y en a qu'un on peut le garder
# puisqu'aucun autre nombre ne pourra s'ajouter pour donner une somme
# divisible par k. S'il y en plus qu'un, on ne peut garder aucun.
# - si k est pair, même chose: un seul diviseur de k/2 => on le garde,
# plus qu'un diviseur de k/2 => on les rejette tous
restes = [0] * k
for i in arr:
restes[i % k] += 1
nb = min(restes[0], 1)
for r in range(1, k // 2 + 1):
if r != k - r:
nb += max(restes[r], restes[k - r])
else:
nb += min(1, restes[r])
return nb
if __name__ == "__main__":
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
arr = list(map(int, input().strip().split(' ')))
result = nonDivisibleSubset(k, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Sock Merchant
# How many pairs of socks John can sell?
#
# https://www.hackerrank.com/challenges/sock-merchant/problem
#
#!/bin/python3
import sys
import itertools
def sockMerchant(n, ar):
# Complete this function
# - trie le tableau des codes couleur
# - itertools.groupby retourne les groupes de valeurs identiques
# - le nombre de paires de valeurs identiques est la moitié
return sum(len(list(g)) // 2 for k, g in itertools.groupby(sorted(ar)))
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = sockMerchant(n, ar)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Between Two Sets
# Find the number of integers that satisfies certain criteria relative to two sets.
#
# https://www.hackerrank.com/challenges/between-two-sets/problem
#
import math
import functools
def gcd(*numbers):
""" greatest common divisor """
return functools.reduce(math.gcd, numbers)
def lcm(*numbers):
""" least common multiple """
return functools.reduce(lambda a, b: (a * b) // gcd(a, b), numbers, 1)
def getTotalX(a, b):
# Complete this function
f = lcm(*a) # ppcm
k = f
n = 0
while k <= max(b):
if all(i % k == 0 for i in b):
n += 1 # tous les nombres b sont multiples de k (un multiple de f)
k += f
return n
if __name__ == "__main__":
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
total = getTotalX(a, b)
print(total)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Repeated String
# Find and print the number of letter a's in the first n letters of an infinitely large periodic string.
#
# https://www.hackerrank.com/challenges/repeated-string/problem
#
def repeatedString(s, n):
# Complete this function
q, r = divmod(n, len(s))
# répétitions de la chaine entière
nb = q * sum(1 for c in s if c == 'a')
# la portion de la chaine qui reste pour atteindre les n lettres
nb += sum(1 for c in s[0:r] if c == 'a')
return nb
if __name__ == "__main__":
s = input()
n = int(input())
result = repeatedString(s, n)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
-- Extra Long Factorials
-- Calculate a very large factorial that doesn't fit in the conventional numeric data types.
--
-- https://www.hackerrank.com/challenges/extra-long-factorials/problem
--
import Control.Applicative
import Control.Monad
import System.IO
fac :: Integer -> Integer
fac 1 = 1
fac n = n * fac (n - 1)
main :: IO ()
main = do
n_temp <- getLine
let n = read n_temp :: Integer
let result = fac n
print result
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Jumping on the Clouds
# Jumping on the clouds
#
# https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
#
# il faut raisonner en partant de la fin et en essayant
# de faire des bonds 2 autant que possibe
ORDINARY_CLOUD = 0
THUNDER_CLOUD = 1
def jumpingOnClouds(c):
i = len(c) - 1
jumps = 0
while i > 0:
jumps += 1
if i >- 2 and c[i - 2] == ORDINARY_CLOUD:
i -= 2
else:
assert c[i - 1] == ORDINARY_CLOUD
i -= 1
return jumps
if __name__ == "__main__":
input()
c = list(map(int, input().split()))
result = jumpingOnClouds(c)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
// Electronics Shop
// Determine the most expensive Keyboard and USB drive combination Monica can purchase within her budget.
//
// https://www.hackerrank.com/challenges/electronics-shop/problem
//
#include <bits/stdc++.h>
using namespace std;
int getMoneySpent(const vector<int>& keyboards, const vector<int>& drives, int s)
{
// Complete this function
int smax = -1;
for (const auto& k : keyboards)
{
for (const auto& d : drives)
{
if (k + d <= s && k + d > smax)
{
smax = k + d;
}
}
}
return smax;
}
int main() {
int s;
int n;
int m;
cin >> s >> n >> m;
vector<int> keyboards(n);
for(int keyboards_i = 0; keyboards_i < n; keyboards_i++){
cin >> keyboards[keyboards_i];
}
vector<int> drives(m);
for(int drives_i = 0; drives_i < m; drives_i++){
cin >> drives[drives_i];
}
// The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
int moneySpent = getMoneySpent(keyboards, drives, s);
cout << moneySpent << endl;
return 0;
}
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Happy Ladybugs
# Determine whether or not all the ladybugs can be made happy.
#
# https://www.hackerrank.com/challenges/happy-ladybugs/problem
#
import itertools
def happyLadybugs(b):
# y a-t-il une case vide ?
if b.count('_') == 0:
# non: il faut alors que le board soit déjà happy
for k, g in itertools.groupby(b):
if len(list(g)) < 2: return "NO"
return "YES"
# ici, on a une empty cell
# pour arriver à rendre les ladybugs happy,
# il faut qu'il y en ait au moins 2 de chaque
# (on ne calcule pas les mouvements)
ladybugs = [0] * 26
for c in b:
if c != '_':
ladybugs[ord(c) - ord('A')] += 1
# une coccinelle d'un seul type: jamais heureuse
if any(map(lambda x: x == 1, ladybugs)): return "NO"
return "YES"
if __name__ == '__main__':
for _ in range(int(input())):
input()
b = input()
print(happyLadybugs(b))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Circular Array Rotation
# Print the elements in an array after 'm' right circular rotation operations.
#
# https://www.hackerrank.com/challenges/circular-array-rotation/problem
#
if __name__ == "__main__":
n, k, q = map(int, input().split())
a = list(map(int, input().split()))
# fait la rotation circulaire
# en Python, c'est ultra-simple
k = n - k % n
a = a[k:] + a[:k]
for _ in range(q):
i = int(input())
print(a[i])
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Cut the sticks
# Given the lengths of n sticks, print the number of sticks that are left before each cut operation.
#
# https://www.hackerrank.com/challenges/cut-the-sticks/problem
#
def cutTheSticks(arr):
# Complete this function
# algorithme:
# il faut soustraire la valeur minimale à chaque fois
# et supprimer les éléments minimaux
def iter():
m = min(arr)
for i in arr:
if i > m:
yield i - m
while len(arr) > 0:
print(len(arr))
arr = list(iter())
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
cutTheSticks(arr)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Queen's Attack II
# Find the number of squares the queen can attack.
#
# https://www.hackerrank.com/challenges/queens-attack-2/problem
#
def queensAttack(n, k, r_q, c_q, obstacles):
# Complete this function
a_d = n - c_q
a_g = c_q - 1
a_h = r_q - 1
a_b = n - r_q
a_bd = min(n - r_q, n - c_q)
a_bg = min(n - r_q, c_q - 1)
a_hd = min(r_q - 1, n - c_q)
a_hg = min(r_q - 1, c_q - 1)
for o in obstacles:
r, c = o
if r == r_q:
if c > c_q: # droite
a_d = min(a_d, c - c_q - 1)
else: # gauche
a_g = min(a_g, c_q - c - 1)
elif c == c_q:
if r > r_q: # bas
a_b = min(a_b, r - r_q - 1)
else: # haut
a_h = min(a_h, r_q - r - 1)
elif c - c_q == r - r_q:
if c > c_q: # bas droite
a_bd = min(a_bd, min(r - r_q - 1, c - c_q - 1))
else: # haut gauche
a_hg = min(a_hg, min(r_q - r - 1, c_q - c - 1))
elif c - c_q == r_q - r:
if c > c_q: # haut droite
a_hd = min(a_hd, min(r_q - r - 1, c - c_q - 1))
else: # bas gauche
a_bg = min(a_bg, min(r - r_q - 1, c_q - c - 1))
return a_d + a_g + a_h + a_b + a_bd + a_bg + a_hd + a_hg
def queensAttack0(n, k, r_q, c_q, obstacles):
# Complete this function
c_q -= 1
r_q -= 1
chess = [True] * (n * n)
a = 0
def xy(c, r):
ok = c < n and r < n and c >= 0 and r >= 0 and chess[c + r * n]
return ok
def check(ic, ir):
nonlocal a
i = 1
while xy(c_q + ic * i, r_q + ir * i):
i += 1
a += 1
for o in obstacles:
chess[o[1] - 1 + n * (o[0] - 1)] = False
check(0, 1) # vers le bas
check(0, -1) # vers le haut
check(1, 0) # vers la droite
check(-1, 0) # vers la gauche
check(1, 1) # bas/droite
check(-1, 1) # bas/gauche
check(1, -1) # haut/droite
check(-1, -1) # haut/gauche
return a
if __name__ == "__main__":
n, k = map(int, input().split())
r_q, c_q = map(int, input().split())
obstacles = []
for _ in range(k):
obstacles.append(list(map(int, input().split())))
result = queensAttack(n, k, r_q, c_q, obstacles)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Grading Students
# Round student grades according to Sam's rules.
#
# https://www.hackerrank.com/challenges/grading/problem
#
import sys
def solve(grades):
# Complete this function
r = []
for g in grades:
if g >= 38:
if ((g + 4) // 5) * 5 - g < 3: g = ((g + 4) // 5) * 5
r.append(g)
return r
n = int(input().strip())
grades = []
grades_i = 0
for grades_i in range(n):
grades_t = int(input().strip())
grades.append(grades_t)
result = solve(grades)
print ("\n".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Library Fine
# Help your library calculate fees for late books!
#
# https://www.hackerrank.com/challenges/library-fine/problem
#
def libraryFine(d1, m1, y1, d2, m2, y2):
# Complete this function
if y1 > y2:
return 10000 # plus d'un an de retard
elif y1 == y2:
if m1 > m2:
return (m1 - m2) * 500 # plus d'un mois de retard
elif m1 == m2:
if d1 > d2:
return (d1 - d2) * 15 # retard dans le même mois
return 0 # retour avant ou à l'échéance
if __name__ == "__main__":
d1, m1, y1 = input().strip().split(' ')
d1, m1, y1 = [int(d1), int(m1), int(y1)]
d2, m2, y2 = input().strip().split(' ')
d2, m2, y2 = [int(d2), int(m2), int(y2)]
result = libraryFine(d1, m1, y1, d2, m2, y2)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Chocolate Feast
# Calculate the number of chocolates that can be bought following the given conditions.
#
# https://www.hackerrank.com/challenges/chocolate-feast/problem
#
def chocolateFeast(n, c, m):
# Complete this function
wrappers = choco = n // c # nombre de choco achetés
while wrappers >= m: # il a assez d'emballage pour échanger un choco
wrappers -= m # échange m wrappers contre
choco += 1 # un choco
wrappers += 1 # et il récupère un emballage
return choco
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
n, c, m = input().strip().split(' ')
n, c, m = [int(n), int(c), int(m)]
result = chocolateFeast(n, c, m)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Bon Appétit
# Determine whether or not Brian overcharged Anna for their split bill.
#
# https://www.hackerrank.com/challenges/bon-appetit/problem
#
n, k = map(int, input().split())
b = list(map(int, input().split()))
p = int(input())
cc = sum(v for i, v in enumerate(b) if i != k)
brian = cc / 2 + b[k - 1]
anna = cc / 2
if p == anna:
print('Bon Appetit')
else:
print(round(p - anna))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Picking Numbers
# What's the largest size subset can you choose from an array such that the difference between any two integers is not bigger than 1?
#
# https://www.hackerrank.com/challenges/picking-numbers/problem
#
def pickingNumbers(a):
# Complete this function
# pour chaque nombre i de a, je cherche combien de nombres
# sont égaux ou +1
return max(sum(1 for j in a if 0 <= j - i <= 1) for i in a)
if __name__ == "__main__":
n = int(input())
a = list(map(int, input().split()))
result = pickingNumbers(a)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# ACM ICPC Team
# Print the maximum topics a given team can cover for ACM ICPC World Finals
#
# https://www.hackerrank.com/challenges/acm-icpc-team/problem
#
import itertools
def acmTeam(topic):
# Complete this function
bt = [int(i, 2) for i in topic]
def count_bits(i):
return bin(i).count('1')
# n = 0
# while i != 0:
# i, r = divmod(i, 2)
# n += r
# return n
bmax = 0
bmax_count = 0
for i, j in itertools.combinations(bt, 2):
b = count_bits(i | j)
if b > bmax:
bmax = b
bmax_count = 1
elif b == bmax:
bmax_count += 1
return bmax, bmax_count
if __name__ == "__main__":
n, m = map(int, input().split())
topic = []
topic_i = 0
for topic_i in range(n):
topic_t = input().strip()
topic.append(topic_t)
result = acmTeam(topic)
print ("\n".join(map(str, result)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Apple and Orange
# Find the respective numbers of apples and oranges that fall on Sam's house.
#
# https://www.hackerrank.com/challenges/apple-and-orange/problem
#
def countApplesAndOranges(s, t, a, b, apples, oranges):
# Complete this function
print(sum(1 for i in apples if s <= (a + i) <= t))
print(sum(1 for i in oranges if s <= (b + i) <= t))
if __name__ == "__main__":
s, t = map(int, input().split())
a, b = map(int, input().split())
m, n = map(int, input().split())
apple = map(int, input().split())
orange = map(int, input().split())
countApplesAndOranges(s, t, a, b, apple, orange)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Jumping on the Clouds: Revisited
# Determine the amount of energy Aerith has after the cloud game ends.
#
# https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited/problem
#
import sys
def jumpingOnClouds(c, k):
# Complete this function
return 100 - sum(c[i] * 2 + 1 for i in range(0, len(c), k))
if __name__ == "__main__":
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
c = list(map(int, input().strip().split(' ')))
result = jumpingOnClouds(c, k)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Equalize the Array
# Delete a minimal number of elements from an array so that all elements of the modified array are equal to one another.
#
# https://www.hackerrank.com/challenges/equality-in-a-array/problem
#
# il faut déterminer quel est l'élément le plus fréquent dans le tableau:
# ça minimisera le nombre d'éléments à retirer pour garder la même valeur
def equalizeArray(arr):
nb = {} # defaultdict(int)
nmax = 0
for i in arr:
n = nb.get(i, 0) + 1
if n > nmax:
nmax = n
nb[i] = n
return len(arr) - nmax
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = equalizeArray(arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Matrix Layer Rotation
# Rotate the matrix R times and print the resultant matrix.
#
# https://www.hackerrank.com/challenges/matrix-rotation-algo/problem
#
# pour mise au point
verbose = False
def rotate(l, n):
n = n % len(l)
return l[n:] + l[:n]
def matrixRotation(matrix, r):
# Complete this function
if verbose:
for row in matrix:
print(' '.join("{:2}".format(i) for i in row))
m = len(matrix[0]) # nombre de colonnes
n = len(matrix) # nombre de lignes
for i in range(0, min(m, n) // 2):
# crée un tableau qui contient les éléments à tourner
# nécessaire, sinon certains testcases tombent en timeout
c = []
# ligne du haut
c.extend(matrix[i][i:m-i])
# colonne à droite
for j in range(i + 1, n - i - 1):
c.append(matrix[j][m-i-1])
# ligne du bas
c.extend(reversed(matrix[n-1-i][i:m-i]))
# colonne à gauche
for j in range(n-1-i-1, i, -1):
c.append(matrix[j][i])
# effectue la rotation
c = rotate(c, r)
# remplace dans la matrice les éléments tournés
k = 0
# ligne du haut (optimisable...)
for j in range(i, m - i):
matrix[i][j] = c[k]
k += 1
# colonne de droite
for j in range(i + 1, n - i - 1):
matrix[j][m - i - 1] = c[k]
k += 1
# ligne du bas (optimisable aussi...)
for j in range(m - 1 - i, i - 1, -1):
matrix[n - 1 - i][j] = c[k]
k += 1
# colonne de gauche
for j in range(n - i - 2, i, -1):
matrix[j][i] = c[k]
k+=1
if verbose:
print("après {} rotations".format(r))
for row in matrix:
print(' '.join("{:2}".format(i) for i in row))
else:
for row in matrix:
print(' '.join(str(i) for i in row))
if __name__ == "__main__":
m, n, r = map(int, input().split(' '))
matrix = []
for matrix_i in range(m):
matrix_t = list(map(int, input().split(' ')))
matrix.append(matrix_t)
matrixRotation(matrix, r)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
add_hackerrank_py(library-fine.py)
add_hackerrank_py(cut-the-sticks.py)
add_hackerrank_py(climbing-the-leaderboard.py)
add_hackerrank_py(manasa-and-stones.py)
add_hackerrank_py(breaking-best-and-worst-records.py)
add_hackerrank_py(drawing-book.py)
add_hackerrank_py(chocolate-feast.py)
add_hackerrank_py(flatland-space-stations.py)
add_hackerrank_py(sherlock-and-squares.py)
add_hackerrank_py(bigger-is-greater.py)
add_hackerrank_py(apple-and-orange.py)
add_hackerrank_py(non-divisible-subset.py)
add_hackerrank_py(encryption.py)
add_hackerrank_py(migratory-birds.py)
add_hackerrank_py(find-digits.py)
add_hackerrank_py(absolute-permutation.py)
add_hackerrank_py(grading.py)
add_hackerrank_py(jumping-on-the-clouds.py)
add_hackerrank_py(save-the-prisoner.py)
add_hackerrank(cavity-map cavity-map.cpp)
add_hackerrank_py(day-of-the-programmer.py)
add_hackerrank_py(sock-merchant.py)
add_hackerrank_py(happy-ladybugs.py)
add_hackerrank_py(append-and-delete.py)
add_hackerrank_py(picking-numbers.py)
add_hackerrank(electronics-shop electronics-shop.cpp)
add_hackerrank_py(cats-and-a-mouse.py)
add_hackerrank(counting-valleys counting-valleys.cpp)
add_hackerrank_py(almost-sorted.py)
add_hackerrank_py(divisible-sum-pairs.py)
add_hackerrank_py(repeated-string.py)
add_hackerrank_py(fair-rations.py)
add_hackerrank_py(the-time-in-words.py)
add_hackerrank_py(strange-advertising.py)
add_hackerrank_py(magic-square-forming.py)
add_hackerrank_py(kaprekar-numbers.py)
add_hackerrank_py(queens-attack-2.py)
add_hackerrank_py(taum-and-bday.py)
add_hackerrank_py(strange-code.py)
add_hackerrank_py(the-grid-search.py)
add_hackerrank_py(circular-array-rotation.py)
add_hackerrank_py(kangaroo.py)
add_hackerrank_py(matrix-rotation-algo.py)
add_hackerrank_py(designer-pdf-viewer.py)
add_hackerrank_py(equality-in-a-array.py)
add_hackerrank_py(angry-professor.py)
add_hackerrank_py(service-lane.py)
add_hackerrank_py(between-two-sets.py)
add_hackerrank_py(the-hurdle-race.py)
add_hackerrank_py(minimum-distances.py)
add_hackerrank_py(extra-long-factorials.py)
add_hackerrank_py(beautiful-days-at-the-movies.py)
add_hackerrank_py(beautiful-triplets.py)
add_hackerrank_py(acm-icpc-team.py)
add_hackerrank_py(jumping-on-the-clouds-revisited.py)
add_hackerrank_py(utopian-tree.py)
add_hackerrank_py(lisa-workbook.py)
add_hackerrank_py(the-birthday-bar.py)
add_hackerrank_py(organizing-containers-of-balls.py)
add_hackerrank_py(permutation-equation.py)
add_hackerrank_py(bon-appetit.py)
add_hackerrank_py(halloween-sale.py)
add_hackerrank(two-pluses two-pluses.cpp)
dirty_cpp(two-pluses)
dirty_cpp(electronics-shop)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Viral Advertising
# How many people will know about the new product after n days?
#
# https://www.hackerrank.com/challenges/strange-advertising/problem
#
def viralAdvertising(n):
people = 5 # jour 1: 5 personnes reçoivent la pub
like = 0
for _ in range(n):
people = people // 2 # la moitié like et retransmettent ...
like += people # on compte les personnes qui like
people = people * 3 # ... à 3 autres personnes
return like
if __name__ == "__main__":
n = int(input())
result = viralAdvertising(n)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Beautiful Triplets
#
#
# https://www.hackerrank.com/challenges/beautiful-triplets/problem
#
def beautifulTriplets(d, arr):
# utilise une indirection pour vérifier l'existence du triplet
# (sinon ça risque d'être trop lent). ici algo en O(n)
numbers = [False] * (20000 + 1)
nb = 0
for a in arr:
# a-t-on un triplet ?
if a - 2 * d >= 0 and numbers[a - d] and numbers[a - 2 * d]:
nb += 1
# mémorise la présence du nombre
numbers[a] = True
return nb
if __name__ == "__main__":
n, d = map(int, input().split())
arr = list(map(int, input().split()))
result = beautifulTriplets(d, arr)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Migratory Birds
# Determine which type of bird in a flock occurs at the highest frequency.
#
# https://www.hackerrank.com/challenges/migratory-birds/problem
#
def migratoryBirds(n, ar):
# Complete this function
nb = [0] * 6
for i in ar:
nb[i] += 1
m = max(nb)
for i, n in enumerate(nb):
if n == m:
return i
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = migratoryBirds(n, ar)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Save the Prisoner!
# Given M sweets and a circular queue of N prisoners, find the ID of the last prisoner to receive a sweet.
#
# https://www.hackerrank.com/challenges/save-the-prisoner/problem
#
def saveThePrisoner(n, m, s):
# Complete this function
# le résultat est l'addition du numéro du prisionnier et du nombre
# de bonbons modulo le nombre de prisonniers. -1 parce qu'il faut
# compter en partant de 0, et +1 parce que les numéros commencent à 1
return 1 + (s - 1 + m - 1) % n
t = int(input())
for a0 in range(t):
n, m, s = map(int, input().split())
result = saveThePrisoner(n, m, s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Forming a Magic Square
# Find the minimum cost of converting a 3 by 3 matrix into a magic square.
#
# https://www.hackerrank.com/challenges/magic-square-forming/problem
#
#!/bin/python3
import sys
import operator
# il n'y a que 8 magic squares 3x3 avec [1..9]
# liste ici par exemple: https://mindyourdecisions.com/blog/2015/11/08/how-many-3x3-magic-squares-are-there-sunday-puzzle/
MAGIC_SQUARES = [
[8, 1, 6, 3, 5, 7, 4, 9, 2],
[6, 1, 8, 7, 5, 3, 2, 9, 4],
[6, 1, 8, 7, 5, 3, 2, 9, 4],
[4, 9, 2, 3, 5, 7, 8, 1, 6],
[2, 9, 4, 7, 5, 3, 6, 1, 8],
[8, 3, 4, 1, 5, 9, 6, 7, 2],
[4, 3, 8, 9, 5, 1, 2, 7, 6],
[6, 7, 2, 1, 5, 9, 8, 3, 4],
[2, 7, 6, 9, 5, 1, 4, 3, 8],
]
def formingMagicSquare(s):
return min(sum(map(abs, map(operator.sub, s, m))) for m in MAGIC_SQUARES)
if __name__ == "__main__":
s = []
for _ in range(3):
s.extend(map(int, input().split()))
result = formingMagicSquare(s)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# The Hurdle Race
# Can you help Dan determine the minimum number of magic beverages he must drink to jump all the hurdles?
#
# https://www.hackerrank.com/challenges/the-hurdle-race/problem
#
def hurdleRace(k, height):
# Complete this function
return max(0, max(height) - k)
if __name__ == "__main__":
n, k = map(int, input().split())
height = list(map(int, input().split(' ')))
result = hurdleRace(k, height)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Absolute Permutation
# Find lexicographically smallest absolute permutation.
#
# https://www.hackerrank.com/challenges/absolute-permutation/problem
#
import sys
import itertools
""" trop lent !
def abs_perm(n, k):
for p in itertools.permutations(range(1, n + 1)):
if all(abs(i - pi) == k for i, pi in enumerate(p, 1)):
return p
return [-1]
"""
def abs_perm(n, k):
if k == 0:
return [i for i in range(1, n + 1)]
if n % (k * 2) != 0:
return [-1]
r = []
sign = 1
for i in range(1, n + 1):
x = i + k * sign
r.append(x)
if i % k == 0: sign = -sign
#assert all(abs(i - v)==k for i, v in enumerate(r, 1))
#assert len(r) == n
#assert sorted(r) == [i for i in range(1, n + 1)]
return r
t = int(input().strip())
for a0 in range(t):
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
r = abs_perm(n, k)
print(' '.join(map(str, r)))
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# Designer PDF Viewer
# Help finding selection area in PDF Viewer.
#
# https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
#
def designerPdfViewer(h, word):
# Complete this function
return max(h[ord(c) - ord('a')] for c in word) * len(word)
if __name__ == "__main__":
h = list(map(int, input().strip().split(' ')))
word = input().strip()
result = designerPdfViewer(h, word)
print(result)
| {
"repo_name": "rene-d/hackerrank",
"stars": "65",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.