code
stringlengths
0
672k
language
stringclasses
2 values
AST_depth
int64
-1
40
alphanumeric_fraction
float64
0
1
max_line_length
int64
0
672k
avg_line_length
float64
0
267k
num_lines
int64
0
4.06k
task
stringlengths
7
14k
source
stringclasses
2 values
from collections import Counter class Solution: def findSubString(self, str1): length = len(str1) dict1 = Counter(str1) k = len(dict1) dict2 = dict() count = 0 start = 0 minimum = 99999 for i in range(length): if count < k: j = start while j < length: if str1[j] not in dict2: dict2[str1[j]] = 1 count += 1 else: dict2[str1[j]] += 1 if count == k: break j += 1 if count == k: minimum = min(minimum, j - i + 1) start = j + 1 dict2[str1[i]] -= 1 if dict2[str1[i]] == 0: dict2.pop(str1[i]) count -= 1 return minimum
python
18
0.543974
37
18.1875
32
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import Counter, defaultdict class Solution: def findSubString(self, str_): set_of_string = set() len_set_of_string = len(set(str_)) answer = float('inf') left = 0 right = 0 freq = defaultdict(int) while right < len(str_): freq[str_[right]] += 1 while left <= right and len(freq) == len_set_of_string: answer = min(answer, right - left + 1) freq[str_[left]] -= 1 if freq[str_[left]] == 0: del freq[str_[left]] left += 1 right += 1 return answer
python
15
0.607843
58
23.285714
21
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, a): dict = {} n = len(set(a)) left = 0 right = 0 ans = len(a) while right < len(a): if a[right] not in dict: dict[a[right]] = 1 else: dict[a[right]] += 1 if len(dict) == n: while dict[a[left]] > 1: dict[a[left]] -= 1 left += 1 ans = min(ans, right - left + 1) right += 1 return ans
python
15
0.518617
36
17.8
20
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
import math class Solution: def findSubString(self, s): dicti = {} mini = math.inf k = len(set(s)) n = len(s) (i, j) = (0, 0) while j < n: if s[j] not in dicti: dicti[s[j]] = 1 else: dicti[s[j]] += 1 if len(dicti) < k: j += 1 elif len(dicti) == k: while len(dicti) == k: mini = min(mini, j - i + 1) if s[i] in dicti: dicti[s[i]] -= 1 if dicti[s[i]] == 0: del dicti[s[i]] i += 1 j += 1 return mini
python
19
0.46875
32
16.777778
27
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import defaultdict class Solution: def findSubString(self, arr): dic = defaultdict(lambda : 0) i = 0 j = 0 n = len(set(arr)) ans = len(arr) while j < len(arr): dic[arr[j]] += 1 if len(dic) < n: j += 1 if len(dic) == n: while dic[arr[i]] > 1: dic[arr[i]] -= 1 i += 1 ans = min(ans, j - i + 1) j += 1 return ans
python
15
0.522427
35
17.047619
21
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): d = {} for i in str: d[i] = 0 i = 0 j = 0 ans = len(str) count = len(d) temp = 0 while j < len(str): while temp < count and j < len(str): if d[str[j]] == 0: temp += 1 d[str[j]] += 1 j += 1 while temp >= count: d[str[i]] -= 1 if d[str[i]] == 0: temp -= 1 i += 1 ans = min(ans, j - i + 1) return ans
python
13
0.460976
39
16.083333
24
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import deque class Solution: def findSubString(self, stre): s = set(stre) set_len = len(s) j = 0 minlen = 1000000000.0 mp = {} n = len(stre) for i in range(n): if stre[i] not in mp: mp[stre[i]] = 1 else: mp[stre[i]] += 1 while j <= i and len(mp) == set_len: if minlen > i - j + 1: minlen = i - j + 1 mp[stre[j]] -= 1 if mp[stre[j]] == 0: del mp[stre[j]] j += 1 return minlen
python
15
0.526432
39
17.916667
24
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): m = {} n = len(set(str)) length = float('inf') j = 0 for i in range(len(str)): m[str[i]] = m.get(str[i], 0) + 1 if len(m) == n: while m[str[j]] > 1: m[str[j]] -= 1 j += 1 length = min(length, i - j + 1) return length
python
15
0.501661
35
19.066667
15
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): dict = {} ans = 1000000000.0 for i in str: if i not in dict: dict[i] = 1 dict2 = {} j = 0 for i in range(len(str)): if str[i] not in dict2: dict2[str[i]] = 1 else: dict2[str[i]] += 1 while len(dict) == len(dict2): ans = min(ans, i - j + 1) if dict2[str[j]] > 1: dict2[str[j]] -= 1 elif dict2[str[j]] == 1: dict2.pop(str[j]) j += 1 return ans
python
16
0.519824
33
18.73913
23
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import defaultdict class Solution: def findSubString(self, s): a = set(s) i = 0 t = {} min_len = float('inf') for j in range(len(s)): if s[j] not in t: t[s[j]] = 0 t[s[j]] += 1 while len(t) == len(a): min_len = min(min_len, j - i + 1) t[s[i]] -= 1 if t[s[i]] == 0: del t[s[i]] i += 1 return min_len
python
15
0.49863
37
17.25
20
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): from collections import defaultdict curr_count = defaultdict(lambda : 0) dist_count = len(set([x for x in str])) if len(str) <= 1: return 1 counter = 0 start = 0 min_len = len(str) for i in range(len(str)): curr_count[str[i]] += 1 if curr_count[str[i]] == 1: counter += 1 if counter == dist_count: while curr_count[str[start]] > 1: if curr_count[str[start]] > 1: curr_count[str[start]] -= 1 start += 1 window_len = i - start + 1 if window_len < min_len: min_len = window_len start_index = start a = min_len return a
python
17
0.594044
41
23.538462
26
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): d = {} for i in str: if i not in d: d[i] = 0 (i, j) = (0, float('inf')) (count, out) = (0, float('inf')) for j in range(len(str)): if d[str[j]] == 0: count += 1 d[str[j]] += 1 if count == len(d): while i < j: d[str[i]] -= 1 if d[str[i]] == 0: out = min(out, j - i + 1) count -= 1 i += 1 break i += 1 return out if out != float('inf') else 1
python
19
0.450431
42
19.173913
23
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): k = len(set(str)) memo = {} ans = len(str) (i, j) = (0, 0) while j < len(str): memo[str[j]] = memo.get(str[j], 0) + 1 if len(memo) < k: j += 1 elif len(memo) == k: while len(memo) == k: memo[str[i]] -= 1 if memo[str[i]] == 0: del memo[str[i]] i += 1 ans = min(ans, j - i + 2) j += 1 elif len(memo) > k: while len(memo) > k: memo[str[i]] -= 1 if memo[str[i]] == 0: del memo[str[i]] i += 1 j += 1 return ans
python
17
0.457721
41
19.148148
27
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): res = 100000 d = {} for i in range(len(str)): if str[i] not in d: d[str[i]] = 0 s1 = set() count = len(d) l = 0 for i in range(len(str)): s1.add(str[i]) d[str[i]] = d[str[i]] + 1 while count == len(s1) and d[str[l]] != 0: d[str[l]] = d[str[l]] - 1 if d[str[l]] == 0: s1.remove(str[l]) res = min(res, i - l + 1) l = l + 1 return res
python
17
0.490783
45
19.666667
21
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): ans = len(str) N = len(str) n = len(set(str)) (i, j) = (0, 0) d = {} while i < N: if str[i] not in d: d[str[i]] = 1 else: d[str[i]] += 1 if len(d) == n: while d[str[j]] > 1: d[str[j]] -= 1 j += 1 ans = min(ans, i - j + 1) i += 1 return ans
python
15
0.444118
30
16
20
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, s): freq = {} for c in s: freq[c] = 0 unique_chars = len(freq) left = 0 right = 0 count = 0 min_length = float('inf') while right < len(s): if s[right] in freq: freq[s[right]] += 1 if freq[s[right]] == 1: count += 1 right += 1 while count == unique_chars: if right - left < min_length: min_length = right - left if s[left] in freq: freq[s[left]] -= 1 if freq[s[left]] == 0: count -= 1 left += 1 return min_length
python
15
0.54049
33
19.423077
26
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): d = {} for i in str: if i not in d: d[i] = 0 x = len(d) ans = 999999 i = 0 j = 0 c = 0 while i < len(str): if d[str[i]] == 0: c += 1 d[str[i]] += 1 if c == x: f = True while c == x: ans = min(ans, i - j + 1) d[str[j]] -= 1 if d[str[j]] == 0: c -= 1 j += 1 i += 1 return ans
python
17
0.410579
30
14.269231
26
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): reslen = len(str) s = set() d = dict() for i in range(len(str)): s.add(str[i]) i = 0 count = 0 for j in range(len(str)): d[str[j]] = d.get(str[j], 0) + 1 if d[str[j]] == 1: count += 1 if count == len(s): while d[str[i]] > 1: if d[str[i]] > 1: d[str[i]] -= 1 i += 1 if reslen > j - i + 1: reslen = j - i + 1 return reslen
python
17
0.47907
35
18.545455
22
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import defaultdict class Solution: def findSubString(self, strr): n = len(strr) dist_count = len(set([x for x in strr])) if n == dist_count: return n curr_count = dict() count = 0 start = 0 min_len = n for i in range(n): curr_count[strr[i]] = curr_count.get(strr[i], 0) + 1 if curr_count[strr[i]] == 1: count += 1 if count == dist_count: while curr_count[strr[start]] > 1: if curr_count[strr[start]] > 1: curr_count[strr[start]] -= 1 start += 1 if min_len > i - start + 1: min_len = i - start + 1 return min_len
python
17
0.584874
55
22.8
25
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, s): n = len(s) res = n i = 0 uniq = set(list(s)) found = {} for j in range(n): if s[j] in found: found[s[j]] += 1 else: found[s[j]] = 1 while i < j: if found[s[i]] > 1: found[s[i]] -= 1 i += 1 else: break if len(found) == len(uniq): res = min(res, j - i + 1) return res
python
15
0.479893
30
15.954545
22
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import defaultdict class Solution: def findSubString(self, s): n = len(s) if n <= 1: return len(s) dis_char = len(set(list(s))) curr = defaultdict(lambda : 0) cnt = 0 minlen = n start = 0 for j in range(n): curr[s[j]] += 1 if curr[s[j]] == 1: cnt += 1 if cnt == dis_char: while curr[s[start]] > 1: curr[s[start]] -= 1 start += 1 length = j - start + 1 if length < minlen: minlen = length startind = start return minlen
python
15
0.560396
35
18.423077
26
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, S): distinct_chars = set(S) n = len(S) left = 0 min_length = n count = [0] * 256 distinct = 0 for right in range(n): count[ord(S[right])] += 1 if count[ord(S[right])] == 1: distinct += 1 if distinct == len(distinct_chars): while count[ord(S[left])] > 1: count[ord(S[left])] -= 1 left += 1 min_length = min(min_length, right - left + 1) count[ord(S[left])] -= 1 left += 1 distinct -= 1 return min_length
python
17
0.563492
50
21.909091
22
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): maxi = len(str) sets = set(str) i = 0 j = 0 m = {} while i < len(str): m[str[i]] = 1 + m.get(str[i], 0) if len(m) >= len(sets): while m[str[j]] > 1: m[str[j]] -= 1 j += 1 maxi = min(maxi, i - j + 1) i += 1 return maxi
python
15
0.47557
35
17.058824
17
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, input_string): start = 0 end = 1 alphabet_dict = {} distinct_list = list(set(input_string)) for i in range(0, len(distinct_list)): alphabet_dict[distinct_list[i]] = 0 n = len(distinct_list) count = 1 alphabet_dict[input_string[0]] = 1 answer = len(input_string) while start <= end < len(input_string): if count < n: element = input_string[end] if alphabet_dict[element] == 0: alphabet_dict[element] = 1 count = count + 1 else: alphabet_dict[element] = alphabet_dict[element] + 1 end = end + 1 elif count == n: answer = min(answer, end - start) element = input_string[start] if element in alphabet_dict and alphabet_dict[element] == 1: count = count - 1 alphabet_dict[element] = alphabet_dict[element] - 1 start = start + 1 while count == n: answer = min(answer, end - start) element = input_string[start] if element in alphabet_dict and alphabet_dict[element] == 1: count = count - 1 alphabet_dict[element] = alphabet_dict[element] - 1 start = start + 1 return answer
python
16
0.63864
64
29.216216
37
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import Counter class Solution: def findSubString(self, str): dic1 = Counter(str) dic2 = dict() (i, j) = (0, 0) res = 10000000000 while j < len(str): if str[j] in dic2: dic2[str[j]] += 1 else: dic2[str[j]] = 1 if len(dic1) == len(dic2): while len(dic1) == len(dic2): res = min(res, j - i + 1) dic2[str[i]] -= 1 if dic2[str[i]] == 0: del dic2[str[i]] i += 1 j += 1 return res
python
17
0.528509
33
18.826087
23
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
import math class Solution: def findSubString(self, s): freq = {} for c in s: freq[c] = 0 (b, d, ans) = (0, 0, math.inf) for (i, c) in enumerate(s): while d == len(freq.keys()): freq[s[b]] -= 1 if freq[s[b]] == 0: ans = min(ans, i - b) d -= 1 b += 1 freq[c] += 1 if freq[c] == 1: d += 1 while d == len(freq.keys()): freq[s[b]] -= 1 if freq[s[b]] == 0: ans = min(ans, i - b + 1) d -= 1 b += 1 return ans
python
16
0.452431
32
17.192308
26
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): n = len(str) ans = 0 length = n s = list(set(str)) d = dict() count = 0 start = 0 for i in range(n): if str[i] not in d.keys(): d[str[i]] = 1 count += 1 else: d[str[i]] += 1 if count == len(s): while d[str[start]] > 1: d[str[start]] -= 1 start += 1 ans = i - start + 1 if length > ans: length = ans return length
python
15
0.505855
30
16.791667
24
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import defaultdict class Solution: def findSubString(self, s): control = set(s) m = len(control) n = len(s) test = defaultdict(lambda : 0) mini = float('inf') i = 0 for j in range(n): while len(test) < m and i < n: test[s[i]] += 1 i += 1 if len(test) < m: break mini = min(mini, i - j) test[s[j]] -= 1 if test[s[j]] == 0: del test[s[j]] return mini
python
13
0.555288
35
17.909091
22
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): i = 0 j = 0 s = len(set(str)) n = len(str) ans = n dic = {} while i < n: if str[i] not in dic: dic[str[i]] = 1 else: dic[str[i]] += 1 if len(dic) == s: while dic[str[j]] > 1: dic[str[j]] -= 1 j += 1 ans = min(ans, i - j + 1) i += 1 return ans
python
15
0.463768
30
15.428571
21
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, s): n = len(s) distinct_chars = len(set(s)) freq = [0] * 256 left = 0 right = 0 count = 0 min_len = n while right < n: ch = ord(s[right]) if freq[ch] == 0: count += 1 freq[ch] += 1 right += 1 while count == distinct_chars: min_len = min(min_len, right - left) ch = ord(s[left]) freq[ch] -= 1 if freq[ch] == 0: count -= 1 left += 1 return min_len
python
14
0.526667
40
17.75
24
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): nd = len(set(str)) i = 0 j = 0 res = len(str) dic = {} while i < len(str): if str[i] in dic: dic[str[i]] = dic[str[i]] + 1 else: dic[str[i]] = 1 if len(dic) == nd: while dic[str[j]] > 1: dic[str[j]] = dic[str[j]] - 1 j = j + 1 res = min(res, i - j + 1) i = i + 1 return res
python
16
0.475936
34
17.7
20
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import Counter class Solution: def findSubString(self, str1): dict1 = dict() count = 0 distinct = len(Counter(str1)) n = len(str1) j = 0 minimum = n for i in range(n): if count < distinct: while j < n: if str1[j] not in dict1: dict1[str1[j]] = 1 count += 1 else: dict1[str1[j]] += 1 if count == distinct: j += 1 break j += 1 if count == distinct: minimum = min(minimum, j - i) dict1[str1[i]] -= 1 if dict1[str1[i]] == 0: dict1.pop(str1[i]) count -= 1 return minimum
python
18
0.546552
33
18.333333
30
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, a): s = '' a1 = {} for i in a: a1[i] = 1 c1 = len(a1) i = 0 j = 0 a2 = {} c = 0 res = len(a) while j < len(a): if a[j] not in a2: a2[a[j]] = 0 c += 1 a2[a[j]] += 1 while i <= j and c == c1: res = min(res, j - i + 1) a2[a[i]] -= 1 if a2[a[i]] == 0: del a2[a[i]] c -= 1 i += 1 j += 1 return res
python
15
0.399015
29
14.037037
27
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): ans_len = len(set(str)) d = {} ws = 0 ans = 10 ** 6 for we in range(0, len(str)): d[str[we]] = d.get(str[we], 0) + 1 if len(d) == ans_len: while d[str[ws]] > 1: d[str[ws]] -= 1 ws += 1 ans = min(ans, we - ws + 1) return ans
python
15
0.5
37
19.533333
15
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): unique = set(str) res = len(str) j = 0 map = dict() for i in range(0, len(str)): if str[i] in map.keys(): map[str[i]] += 1 else: map[str[i]] = 1 if len(unique) == len(map): while map[str[j]] > 1: map[str[j]] -= 1 j += 1 res = min(res, i - j + 1) return res
python
15
0.511364
30
18.555556
18
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): l = len(str) s = set() for i in range(len(str)): s.add(str[i]) n = len(s) head = 0 tail = 0 hmap = {} ans = l while head < l: if str[head] in hmap: hmap[str[head]] += 1 else: hmap[str[head]] = 1 if len(hmap) == n: while hmap[str[tail]] > 1: hmap[str[tail]] -= 1 tail += 1 ans = min(ans, head - tail + 1) head += 1 return ans
python
15
0.516129
35
17.083333
24
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from collections import defaultdict, Counter from sys import maxsize class Solution: def findSubString(self, str): cnt = Counter(str) cur = defaultdict(int) k = 0 ans = maxsize i = 0 for (j, ch) in enumerate(str): cur[ch] += 1 if cur[ch] == 1: k += 1 if k == len(cnt): while i < j: if cur[str[i]] == 1: break cur[str[i]] -= 1 i += 1 ans = min(ans, j - i + 1) return ans
python
15
0.552448
44
17.652174
23
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): res = float('inf') (i, j) = (0, 0) maxLen = len(set(list(str))) hashmap = {} while j < len(str): if str[j] not in hashmap: hashmap[str[j]] = 1 else: hashmap[str[j]] += 1 j += 1 if len(hashmap) == maxLen: while i < j and hashmap[str[i]] > 1: hashmap[str[i]] -= 1 i += 1 res = min(res, j - i) return res
python
15
0.5275
40
20.052632
19
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): d = {} for ch in str: if ch not in d: d[ch] = 1 n = len(d) d.clear() i = 0 j = 0 count = 0 mini = len(str) while j < len(str): if str[j] not in d: d[str[j]] = 1 count = count + 1 else: d[str[j]] = d[str[j]] + 1 if count == n: while d[str[i]] != 1: d[str[i]] = d[str[i]] - 1 i = i + 1 mini = min(mini, j - i + 1) j = j + 1 return mini
python
16
0.461197
31
16.346154
26
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, s): n = len(s) d = {} count = 0 for i in range(n): d[s[i]] = 0 i = 0 j = 0 ans = n while i < n: if d[s[i]] == 0: count += 1 d[s[i]] += 1 if count == len(d): while j < n and d[s[j]] > 1: d[s[j]] -= 1 j += 1 if ans > i - j + 1: ans = i - j + 1 i += 1 return ans
python
15
0.411602
32
14.73913
23
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): p = len(set(str)) j = 0 i = 0 d = {} mn = 100000 while j < len(str): if str[j] in d: d[str[j]] += 1 else: d[str[j]] = 1 if len(d) == p: while len(d) == p: mn = min(mn, j - i + 1) d[str[i]] -= 1 if d[str[i]] == 0: del d[str[i]] i += 1 j += 1 return mn
python
17
0.432507
30
15.5
22
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): d = {} i = 0 j = 0 sw = 100000000 n = len(set(str)) while j < len(str): if str[j] not in d: d[str[j]] = 1 else: d[str[j]] += 1 if len(d) == n: while len(d) == n: sw = min(sw, j - i + 1) d[str[i]] -= 1 if d[str[i]] == 0: del d[str[i]] i += 1 j += 1 return sw
python
17
0.440541
30
15.818182
22
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): dict = {} for i in str: if i in dict: dict[i] += 1 else: dict[i] = 1 count = len(list(dict.keys())) i = j = 0 ans = len(str) c = 0 dict = {} for i in range(len(str)): if str[i] in dict: dict[str[i]] += 1 else: dict[str[i]] = 1 c += 1 if c == count: ans = min(ans, i - j + 1) while c == count and j <= i: dict[str[j]] -= 1 if dict[str[j]] == 0: del dict[str[j]] c -= 1 ans = min(ans, i - j + 1) j += 1 return ans
python
17
0.464738
32
17.433333
30
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
class Solution: def findSubString(self, str): s = set(str) n = len(s) ss = set() ind = 0 d = {} mini = 10 ** 9 for i in range(len(str)): if str[i] not in ss: ss.add(str[i]) d[str[i]] = d.get(str[i], 0) + 1 if len(ss) == n: ind = i + 1 mini = min(mini, i + 1) break index = 0 while d[str[index]] > 1: d[str[index]] -= 1 index += 1 mini = min(mini, i - index + 1) for i in range(ind, len(str)): d[str[i]] = d.get(str[i], 0) + 1 while d[str[index]] > 1: d[str[index]] -= 1 index += 1 mini = min(mini, i - index + 1) while d[str[index]] > 1: d[str[index]] -= 1 index += 1 mini = min(mini, i - index + 1) return mini
python
15
0.497854
35
20.181818
33
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time. For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca. Example 1: Input : "AABBBCBBAC" Output : 3 Explanation : Sub-string -> "BAC" Example 2: Input : "aaab" Output : 2 Explanation : Sub-string -> "ab" Example 3: Input : "GEEKSGEEKSFOR" Output : 8 Explanation : Sub-string -> "GEEKSFOR" Your Task: You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string. Expected Time Complexity: O(256.N) Expected Auxiliary Space: O(256) Constraints: 1 ≤ |S| ≤ 10^{5} String may contain both type of English Alphabets.
taco
from math import ceil, log, floor, sqrt, gcd for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) f = {} for i in l: try: f[i] += 1 except: f[i] = 1 if max(f.values()) > n // 2 or len(set(l)) <= 2: print('NO') else: print('YES') l.sort() print(*l) print(*l[n // 2:] + l[:n // 2])
python
14
0.502976
49
18.764706
17
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
import math import bisect import heapq from math import gcd, floor, sqrt, log from collections import defaultdict as ddc from collections import Counter def intin(): return int(input()) def mapin(): return map(int, input().split()) def strin(): return input().split() INF = 10 ** 20 mod = 1000000007 def exponentiation(bas, exp, mod=1000000007): t = 1 while exp > 0: if exp % 2 != 0: t = t * bas % mod bas = bas * bas % mod exp //= 2 return t % mod def MOD(p, q=1, mod=1000000007): expo = 0 expo = mod - 2 while expo: if expo & 1: p = p * q % mod q = q * q % mod expo >>= 1 return p def process(arr, n): C = Counter(arr) edge = 0 for val in C.values(): if val > n // 2: print('NO') return elif val == n // 2: edge += 1 if len(C.keys()) == edge == 2: print('NO') return print('YES') arr.sort() (B, C) = (arr, arr[(n + 1) // 2:] + arr[:(n + 1) // 2]) r = n - 1 for i in range(n): if i >= r: break if B[i] == C[i]: (C[i], C[r]) = (C[r], C[i]) r -= 1 print(*B) print(*C) def main(): for _ in range(int(input())): n = intin() arr = list(mapin()) process(arr, n) main()
python
12
0.553618
56
15.867647
68
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
tt = int(input()) for _ in range(tt): n = int(input()) a = list(map(int, input().split())) d = {} for i in a: try: d[i] += 1 except KeyError: d[i] = 1 m = max(list(d.values())) k = len(list(d.keys())) if m > n // 2 or k <= 2: print('NO') continue else: print('YES') a.sort() print(*a) print(*a[m:] + a[:m])
python
13
0.495549
36
15.85
20
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from bisect import bisect_left from re import sub import re from typing import DefaultDict import math from collections import defaultdict from math import sqrt import collections from sys import maxsize from itertools import combinations_with_replacement import sys import copy def sieve_erasthones(n): cnt = 0 prime = [True for i in range(n + 1)] p = 2 while p * p <= n: if prime[p] == True: for i in range(p ** 2, n + 1, p): prime[i] = False p += 1 prime[0] = False prime[1] = False for p in range(n + 1): if prime[p]: cnt += 1 return cnt def calculate(p, q): mod = 998244353 expo = 0 expo = mod - 2 while expo: if expo & 1: p = p * q % mod q = q * q % mod expo >>= 1 return p def count_factors(n): i = 1 c = 0 while i <= math.sqrt(n): if n % i == 0: if n // i == i: c += 1 else: c += 2 i += 1 return c def ncr_modulo(n, r, p): num = den = 1 for i in range(r): num = num * (n - i) % p den = den * (i + 1) % p return num * pow(den, p - 2, p) % p def isprime(n): prime_flag = 0 if n > 1: for i in range(2, int(sqrt(n)) + 1): if n % i == 0: prime_flag = 1 break if prime_flag == 0: return True else: return False else: return True def smallestDivisor(n): if n % 2 == 0: return 2 i = 3 while i * i <= n: if n % i == 0: return i i += 2 return n def dict_ele_count(l): d = DefaultDict(lambda : 0) for ele in l: d[ele] += 1 return d def max_in_dict(d): maxi = 0 for ele in d: if d[ele] > maxi: maxi = d[ele] return maxi def element_count(s): l = [] k = s[0] c = 0 for ele in s: if ele == k: c += 1 else: l.append([k, c]) k = ele c = 1 l.append([k, c]) return l def modular_exponentiation(x, y, p): res = 1 x = x % p if x == 0: return 0 while y > 0: if y & 1 != 0: res = res * x % p y = y >> 1 x = x * x % p return res def number_of_primefactor(n): l = [] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: l.append(i) n = n / i if n > 2: l.append(n) return len(set(l)) def twosum(a, n, x): rem = [] for i in range(x): rem.append(0) for i in range(n): if a[i] < x: rem[a[i] % x] += 1 for i in range(1, x // 2): if rem[i] > 0 and rem[x - i] > 0: return True if i >= x // 2: if x % 2 == 0: if rem[x // 2] > 1: return True else: return False elif rem[x // 2] > 0 and rem[x - x // 2] > 0: return True else: return False def divSum(num): result = 0 i = 2 while i <= math.sqrt(num): if num % i == 0: if i == num / i: result = result + i else: result = result + (i + num / i) i = i + 1 return result + 1 + num def subsequence(str1, str2): m = len(str1) n = len(str2) j = 0 i = 0 while j < m and i < n: if str1[j] == str2[i]: j = j + 1 i = i + 1 return j == m def primeFactors(n): d = defaultdict(lambda : 0) while n % 2 == 0: d[2] += 1 n = n / 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: d[int(i)] += 1 n = n / i if n > 2: d[int(n)] += 1 return d def calc(s): ans = 0 for ele in s: ans += ord(ele) - 96 return ans def modInverse(b, m): g = math.gcd(b, m) if g != 1: return -1 else: return pow(b, m - 2, m) def modDivide(a, b, m): a = a % m inv = modInverse(b, m) return inv * a % m def solve(): n = int(input()) d = defaultdict(lambda : 0) l = list(map(int, input().split())) ans = [] for ele in l: d[ele] += 1 if len(d) <= 2: print('NO') return l = sorted(d.items(), key=lambda kv: (kv[1], kv[0]), reverse=True) for ele in l: if ele[1] > n // 2: print('NO') return else: break ans1 = [l[0][0] for _ in range(l[0][1])] ans2 = [l[0][0] for _ in range(l[0][1])] temp1 = [] for i in range(1, len(l)): temp1 += [l[i][0] for _ in range(l[i][1])] ans1 += temp1 ans2 = temp1 + ans2 print('YES') print(*ans1) print(*ans2) for _ in range(int(input())): solve()
python
16
0.532189
67
15.573222
239
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
def go(): for i in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = a b.sort() f = 0 for j in range((n + 1) // 2): if b[j] == b[j + n // 2]: print('NO') f = 1 break if f == 1: continue if n % 2 == 0 and b[0] == b[n // 2 - 1] and (b[n // 2] == b[n - 1]): print('NO') continue c = [] c.extend(b[int(n / 2):]) c.extend(b[:int(n / 2)]) print('YES') print(*b) print(*c) go()
python
15
0.438053
70
17.833333
24
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from collections import defaultdict def solve(): n = int(input()) a = [int(x) for x in input().split()] a.sort() cnt = defaultdict(int) for i in a: cnt[i] += 1 if cnt[i] > n // 2: print('NO') return if n % 2 == 0 and (a[0] == a[n // 2 - 1] and a[n // 2] == a[n - 1]): print('NO') else: print(f"YES\n{' '.join(map(str, a))}\n{' '.join(map(str, a[n // 2:]))} {' '.join(map(str, a[:n // 2]))}") for _ in range(int(input())): solve()
python
18
0.507726
107
24.166667
18
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().split())) arr.sort() x = list(set(arr)) flag = True for i in x: if arr.count(i) > n // 2: flag = False break if flag == True: if len(x) == 2 and arr.count(x[0]) == arr.count(x[1]): print('NO') else: print('YES') print(*arr) x1 = n // 2 print(*arr[x1:] + arr[:x1]) else: print('NO')
python
15
0.5225
56
18.047619
21
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
def solution(): N = int(input()) A = list(map(int, input().split())) A.sort() stat = 1 for i in range((N + 1) // 2): if A[i] == A[i + N // 2]: print('NO') stat = 0 return if stat and N % 2 == 0 and (A[0] == A[N // 2 - 1]) and (A[N // 2] == A[N - 1]): print('NO') else: print('YES') print(' '.join(map(str, A))) print(' '.join(map(str, A[(N + 1) // 2:])), end=' ') print(' '.join(map(str, A[:(N + 1) // 2]))) for _ in range(int(input())): solution()
python
18
0.466527
80
24.157895
19
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from collections import Counter test = int(input()) for _ in range(test): n = int(input()) A = list(map(int, input().split())) c = Counter(A) m = max(c.values()) if m > n // 2 or len(c) <= 2: print('NO') else: print('YES') A.sort() print(*A) p = n // 2 print(*A[p:] + A[:p])
python
13
0.539249
36
18.533333
15
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
t = int(input()) for _ in range(t): n = int(input()) l = list(map(int, input().split())) d = {} for i in l: d[i] = d.get(i, 0) + 1 mx = 0 for i in d.values(): if i >= mx: mx = i if len(d) == 2: print('NO') elif n % 2 == 0: if mx <= n // 2: print('YES') l.sort() for i in range(n): print(l[i], end=' ') print() for i in range(n // 2, n): print(l[i], end=' ') print(end='') for i in range(0, n // 2): print(l[i], end=' ') print() else: print('NO') elif mx < n // 2 + 1: print('YES') l.sort() for i in range(n): print(l[i], end=' ') print() for i in range(n // 2 + 1, n): print(l[i], end=' ') print(end='') for i in range(0, n // 2 + 1): print(l[i], end=' ') print() else: print('NO')
python
15
0.457847
36
17.357143
42
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
tc = int(input()) for t in range(0, tc): length = int(input()) nums = list(map(int, input().split())) Map = {} for n in nums: Map[n] = Map.setdefault(n, 0) + 1 if Map[n] > length // 2: print('NO') break else: if len(Map) == 2 and length % 2 == 0: print('NO') else: freqs = sorted(set(Map.values()), reverse=True) ans = [] for freq in freqs: for (key, value) in Map.items(): if value == freq: ans += [str(key)] * value print('YES') print(' '.join(ans)) print(' '.join(ans[Map[int(ans[0])]:] + ans[:Map[int(ans[0])]]))
python
21
0.536713
67
23.869565
23
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
t = int(input()) for test in range(t): n = int(input()) lst = list(map(int, input().split())) lst.sort() lst2 = lst[n // 2:] + lst[:n // 2] ans = 'YES' for i in range(n): if lst[i] == lst2[i]: ans = 'NO' break p1 = 1 p2 = n - 2 while p1 < p2: temp1 = sorted(lst[p1:p2 + 1]) temp2 = sorted(lst2[p1:p2 + 1]) if temp1 == temp2: ans = 'NO' break p1 += 1 p2 -= 1 print(ans) if ans == 'YES': print(*lst) print(*lst2)
python
13
0.515556
38
17
25
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from math import inf from collections import * import math, os, sys, heapq, bisect, random, threading from functools import lru_cache from itertools import * def inp(): return sys.stdin.readline().rstrip('\r\n') def out(var): sys.stdout.write(str(var)) def inpu(): return int(inp()) def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) (M, M1) = (1000000007, 998244353) def main(): how_much_noob_I_am = 1 how_much_noob_I_am = inpu() for _ in range(1, how_much_noob_I_am + 1): n = inpu() arr = lis() c = Counter(arr) p = sum(c.values()) m = max(c.values()) if p - m < m or (m == n // 2 and len(set(arr)) == 2): print('NO') continue arr.sort() res = arr[(len(arr) + 1) // 2:] + arr[:(len(arr) + 1) // 2] print('YES') print(*arr) print(*res) main()
python
15
0.604103
61
18.897959
49
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for _ in range(int(input())): n = int(input()) l = input().split() d = {} for i in l: i = int(i) if i in d: d[i] += 1 else: d[i] = 1 l = [] for i in d: l.append([i, d[i]]) if len(l) == 1: print('NO') elif len(l) == 2: if l[0][0] == l[1][0] and (l[0][1] == 1 or l[0][1] == 2): print('YES') s = str(l[0][0]) * l[0][1] + str(l[1][0]) * l[0][1] else: print('NO') else: le = n // 2 ma = l[0][1] s = [] for i in l: s[len(s):] = [i[0]] * i[1] if i[1] > ma: ma = i[1] if ma > le: print('NO') else: print('YES') for i in s: print(i, end=' ') print() s = s[le:] + s[0:le] for i in s: print(i, end=' ') print()
python
16
0.409289
59
16.225
40
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
import sys import math from collections import defaultdict, Counter, deque from bisect import * from string import ascii_lowercase from heapq import * def readInts(): x = list(map(int, sys.stdin.readline().rstrip().split())) return x[0] if len(x) == 1 else x def readList(type=int): x = sys.stdin.readline() x = list(map(type, x.rstrip('\n\r').split())) return x def readStr(): x = sys.stdin.readline().rstrip('\r\n') return x write = sys.stdout.write read = sys.stdin.readline def dist(x1, x2, y1, y2): return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) def mergeSort(arr, check=lambda a, b: a < b, reverse=False): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] mergeSort(L, check, reverse) mergeSort(R, check, reverse) i = j = k = 0 while i < len(L) and j < len(R): if check(L[i], R[j]): if not reverse: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 elif not reverse: arr[k] = R[j] j += 1 else: arr[k] = L[i] i += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 def maxSum(arr): max_sum = float('-inf') max_cur = 0 for num in ar: max_cur = max(max_cur + num, num) if max_cur > max_sum: max_sum = max_cur return max_sum def hcf(a, b): if b == 0: return a else: return hcf(b, b % a) def get_power(n, m): i = 1 p = -1 while i <= n: i = i * m p += 1 return p def fact(n): f = 1 for i in range(2, n + 1): f *= i return f def find_closest(num, ar): min_d = float('inf') for num2 in ar: d = abs(num2 - num) if d < min_d: min_d = d return min_d def check_pal(n): s = str(n) j = len(s) - 1 i = 0 while j > i: if s[i] != s[j]: return False i += 1 j -= 1 return True def solve(t): n = readInts() ar = readList() cnt = 0 mx_ele = ar[0] if len(set(ar)) < 3: print('NO') return None for num in ar: if num == mx_ele: cnt += 1 else: cnt -= 1 if cnt == 0: mx_ele = num cnt = 1 if cnt > 0: cnt = 0 for num in ar: if num == mx_ele: cnt += 1 if cnt > n // 2: print('NO') return None res = [] ar.sort() res = ar[n // 2:] + ar[:n // 2] print('YES') print(*ar) print(*res) def main(): t = 1 sys.setrecursionlimit(12000) t = readInts() for i in range(t): solve(i + 1) main()
python
16
0.539737
60
15.454545
143
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) count = {} for i in range(n): if a[i] in count: count[a[i]] += 1 else: count[a[i]] = 1 if len(count.keys()) <= 2: print('NO') elif max(count.values()) > n // 2: print('NO') else: print('YES') pairs = list(count.items()) pairs.sort(key=lambda x: x[1], reverse=True) array1 = [] for pair in pairs: for j in range(pair[1]): array1.append(pair[0]) array2 = [] shift = pairs[0][1] for i in range(n - shift, n): array2.append(array1[i]) for i in range(n - shift): array2.append(array1[i]) print(*array1) print(*array2)
python
14
0.571429
46
20.933333
30
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from collections import Counter for tcase in range(int(input())): n = int(input()) a = Counter(map(int, input().split())).most_common() b = [] for (k, v) in a: b.extend([k] * v) ans = False i = 1 while not ans and i * 2 < len(a): c = [] for (k, v) in a[i:]: c.extend([k] * v) for (k, v) in a[:i]: c.extend([k] * v) ans = all((bi != ci for (bi, ci) in zip(b, c))) i += 1 if ans: print('YES') print(' '.join(map(str, b))) print(' '.join(map(str, c))) else: print('NO')
python
15
0.51992
53
20.826087
23
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
def Print(arr): for ele in arr: print(ele, end=' ') print() t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().split())) arr.sort() ar = arr[n // 2:] for i in range(n // 2): ar.append(arr[i]) ans = True for i in range(n): if arr[i] == ar[i]: ans = False break d = {} for ele in arr: d[ele] = d.get(ele, 0) + 1 if len(d) == 2: tm = [] for ele in d: tm.append(d[ele]) if tm[0] == tm[1]: ans = False if ans: print('YES') Print(arr) Print(ar) else: print('NO')
python
13
0.523364
38
15.71875
32
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for _ in range(int(input())): size = int(input()) L = list(map(int, input().split())) L.sort() s = set(L) c = 0 for i in s: if L.count(i) > size // 2: print('NO') c = 1 break if c == 1: continue if len(s) == 2: print('NO') continue print('YES') print(*L) temp = L[(size + 1) // 2:] + L[:(size + 1) // 2] print(*temp)
python
13
0.5
49
16.3
20
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from math import * a = int(input()) for x in range(a): b = int(input()) c = list(map(int, input().split())) h = {} for y in range(b): if h.get(c[y]) == None: h[c[y]] = 1 else: h[c[y]] += 1 o = b // 2 l = 0 for y in h: if h[y] > o: l = -1 break if len(h) <= 2: print('NO') elif l == -1: print('NO') else: print('YES') c.sort() print(*c) j = c[o:] + c[:o] print(*j)
python
13
0.460591
36
14.037037
27
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from collections import Counter for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) arr.sort() dit = Counter(arr) f = max(dit.values()) if f > n // 2 or len(dit) == 2: print('NO') continue new = arr[n // 2:] + arr[:n // 2] print('YES') print(*arr) print(*new)
python
13
0.576547
38
20.928571
14
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) d = {} for i in a: if i in d: d[i] += 1 else: d[i] = 1 if max(d.values()) > n // 2: print('NO') continue if len(d) == 2: print('NO') continue print('YES') c = [] a.sort() c = a[n // 2:] + a[:n // 2] print(*a) print(*c)
python
13
0.46988
36
14.809524
21
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) arr.sort() flag = False mp = {} for i in arr: if i not in mp: mp[i] = 1 else: mp[i] += 1 if mp[i] > n // 2: flag = True if flag: print('NO') continue if len(mp) == 2: print('NO') continue arr.sort() maxxx = 0 for k in mp: if mp[k] > maxxx: maxxx = mp[k] num = [] num = arr k = maxxx num = num[::-1] xx = num[:k - 1:-1] yy = num[k - 1::-1] num = yy + xx print('YES') print(*arr) print(*num)
python
13
0.507634
38
14.411765
34
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
import math t = int(input()) while t > 0: n = int(input()) a = list(map(int, input().split())) m = 0 d = {} for x in range(n): if a[x] in d: d[a[x]] = d[a[x]] + 1 else: d[a[x]] = 1 m = max(d[a[x]], m) if m > n / 2: print('NO') else: d = list(d.items()) if len(d) <= 2: print('NO') t -= 1 continue print('YES') d = sorted(d, key=lambda x: x[1], reverse=True) for x in d: for y in range(x[1]): print(x[0], end=' ') print() for x in range(1, len(d)): for y in range(d[x][1]): print(d[x][0], end=' ') for y in range(d[0][1]): print(d[0][0], end=' ') print() t -= 1
python
15
0.476874
49
17.441176
34
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for i in range(int(input())): n = int(input()) l = list(map(int, input().split())) lc = [] l.sort() for i in set(l): lc.append(l.count(i)) lc.sort(reverse=True) if lc[0] > n // 2: print('NO') continue if lc[0] + lc[1] == n: print('NO') continue e = lc[0] lans = [] for j in range(n): lans.append(l[(j + e) % n]) print('YES') for j in l: print(j, end=' ') print() for j in lans: print(j, end=' ') print()
python
13
0.529817
36
16.44
25
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from collections import Counter tc = int(input()) for case in range(tc): n = int(input()) a = list(map(int, input().split())) c = Counter(a) nb2 = n // 2 mx = max(c.values()) if mx > nb2 or len(set(a)) == 2: print('NO') continue else: print('YES') a.sort() print(*a, sep=' ') print(*a[mx:] + a[:mx], sep=' ')
python
13
0.554878
36
19.5
16
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
import math T = int(input()) for _ in range(T): N = int(input()) l = list(map(int, input().split())) flag = 'Yes' l.sort() a = 1 m = 0 for i in range(1, N): if l[i - 1] == l[i]: a += 1 else: if m < a: m = a a = 1 if m < a: m = a if m > N // 2: print('NO') continue k = m i = 0 B = l[k:] + l[:k] if l[0] == B[-1] and l[-1] == B[0]: print('NO') continue print('YES') for i in l: print(i, end=' ') print() for i in B: print(i, end=' ') print()
python
13
0.455102
36
13.411765
34
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
from collections import Counter for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) c = Counter(arr) m = max(c.values()) if m >= (n + 1) / 2 or len(set(arr)) <= 2: print('NO') else: for el in c: if c[el] == m: break a = [el] * m b = [] for el in c: if el != a[0]: b += [el] * c[el] print('YES') print(*a + b) print(*b + a)
python
14
0.497449
43
18.6
20
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for cas in range(int(input())): n = int(input()) l = list(map(int, input().split())) l.sort() if len(set(l)) == 1: print('NO') continue if len(set(l)) == 2 and n % 2 == 0: i = 0 j = n - 1 flag = 0 while i < j: if l[i] == l[j]: flag = 1 break i += 1 j -= 1 if not flag: print('NO') continue d = {} flag = 0 for i in l: if i not in d: d[i] = 1 else: d[i] += 1 mx = 0 for i in d: if d[i] > mx: mx = d[i] if mx > n // 2: print('NO') continue else: print('YES') print(*l) print(*l[mx:] + l[:mx])
python
13
0.460177
36
13.868421
38
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) l.sort() pre = 0 xx = 0 d = dict() flag = False c = 0 for x in set(l): d[x] = l.count(x) if d[x] > pre: xx = x pre = d[x] if d[x] > n - d[x]: flag = True break if d[x] == n // 2 and n % 2 == 0: c += 1 if c == 2: flag = True break if flag: print('NO') else: print('YES') index = l.index(xx) while index + 1 < n: if l[index + 1] == xx: index += 1 else: break print(*l) l = l[n // 2:] + l[:n // 2] print(*l)
python
13
0.458781
36
14.942857
35
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
T = int(input()) for _ in range(T): N = int(input()) A = list(map(int, input().split())) A.sort() L = A[N // 2:] L.extend(A[:N // 2]) f = False for i in range(N - 1): if A[i] == L[i]: f = True break if A[i] == L[i + 1] and A[i + 1] == L[i]: f = True break if A[N - 1] == L[N - 1]: f = True if f: print('NO') else: print('YES') print(*A) print(*L)
python
13
0.45953
43
15.652174
23
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
import sys from math import sqrt, gcd, factorial, ceil, floor from collections import deque, Counter, OrderedDict from heapq import heapify, heappush, heappop input = lambda : sys.stdin.readline() I = lambda : int(input()) S = lambda : input().strip() M = lambda : map(int, input().strip().split()) L = lambda : list(map(int, input().strip().split())) mod = 1000000007 for _ in range(I()): n = I() a = L() a.sort() c = a[n // 2:] + a[:n // 2] if any((a[i] == c[i] for i in range(n))) or any((a[i] == c[i + 1] and a[i + 1] == c[i] for i in range(n - 1))): print('NO') continue print('YES') print(*a) print(*c)
python
14
0.603865
112
28.571429
21
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
T = int(input()) for ts in range(T): N = int(input()) A = list(map(int, input().split(' '))) A.sort() C = A.copy() C = C[(N + 1) // 2:N] + C[:(N + 1) // 2] check = True for i in range(N): if A[i] == C[i]: check = False break if N % 2 == 0 and A[N // 2 - 1] == C[N // 2] and (A[N // 2] == C[N // 2 - 1]): check = False if check: print('YES') print(' '.join(map(str, A))) print(' '.join(map(str, C))) else: print('NO')
python
13
0.467416
79
21.25
20
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
t = int(input()) for _ in range(t): n = int(input()) line = input() a = list(map(int, line.split())) a.sort() counts = [[a[0], 1]] curr_value = a[0] for i in range(1, n): if a[i] == curr_value: counts[-1][1] += 1 else: curr_value = a[i] counts.append([a[i], 1]) counts.sort(key=lambda x: x[1], reverse=True) highest_count = counts[0][1] if highest_count > n / 2 or len(counts) == 2: print('NO') else: print('YES') for item in a: print(item, end=' ') print() for i in range(n): index = (i + highest_count) % n print(a[index], end=' ') print()
python
13
0.553663
46
20.740741
27
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
def fi(): return int(input()) def li(): return list(map(int, input().split())) t = fi() for i in range(t): n = fi() a = li() m = {} for e in a: if e not in m: m[e] = 1 else: m[e] += 1 pos = True firstrot = 0 m = dict(sorted(m.items(), key=lambda x: x[1], reverse=True)) for (key, value) in m.items(): if value > n / 2 or (value == n / 2 and len(m.keys()) == 2): pos = False firstrot = value break if not pos: print('NO') else: print('YES') templist = [] for (key, value) in m.items(): for j in range(value): templist.append(key) print(*templist) templist = templist[firstrot:] + templist[:firstrot] print(*templist)
python
14
0.571001
62
18.676471
34
You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied: * There doesn't exist a pair of integers (i, j) such that 1 ≤ i ≤ j ≤ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j]. If there exist such permutations, find any of them. As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}] ------ Input Format ------ - The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows. - The first line of each test case contains a single integer N — the number of integers. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}. ------ Output Format ------ For each test case, if there are no such permutations B and C, output NO. Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}. You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical). ------ Constraints ------ $1 ≤T ≤100$ $3 ≤N ≤1000$ $0 ≤A_{i} ≤10^{9}$ - The sum of $N$ over all test cases doesn't exceed $2000$. ----- Sample Input 1 ------ 3 3 1 1 2 4 19 39 19 84 6 1 2 3 1 2 3 ----- Sample Output 1 ------ NO YES 19 19 39 84 39 84 19 19 YES 1 1 2 2 3 3 2 3 3 1 1 2 ----- explanation 1 ------ Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad: - If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$ - If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$ - If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$ - If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$ - If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$
taco
t = int(input()) for _ in range(t): (a, b) = map(int, input().split()) if a == 0 and b == 0: print(1) elif a == 0: print(0.5) elif b == 0: print(1) elif a > 4 * b: print('%.10f' % ((a - b) / a)) else: print('%.10f' % (a / 16 / b + 0.5))
python
14
0.450593
37
18.461538
13
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading threading.stack_size(10 ** 8) sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) (self.buffer.truncate(0), self.buffer.seek(0)) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda : self.buffer.read().decode('ascii') self.readline = lambda : self.buffer.readline().decode('ascii') (sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout)) input = lambda : sys.stdin.readline().rstrip('\r\n') class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print('Invalid argument to calculate n!') print('n must be non-negative value. But the argument was ' + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print('Invalid argument to calculate n^(-1)') print('n must be non-negative value. But the argument was ' + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print('Invalid argument to calculate (n^(-1))!') print('n must be non-negative value. But the argument was ' + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD t = int(input()) for i in range(t): (a, b) = list(map(int, input().split())) if a == 0 and b == 0: print(1) elif a == 0: print(0.5) elif b == 0: print(1) else: if a < 4 * b: ans = (b * a + a * a / 8) / (2 * a * b) else: ans = 1 - b / a print(ans)
python
17
0.642193
93
26.811189
143
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
from fractions import Fraction t = int(input()) for _ in range(t): (a, b) = map(lambda x: Fraction(x), input().split(' ')) if b == 0: print(1) continue elif a == 0: print(0.5) continue up = a * (b + b + a / 4) / 2 - max(0, a - 4 * b) * (a / 4 - b) / 2 down = a * 2 * b print(float(up / down))
python
12
0.517915
67
22.615385
13
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
t = int(input()) for i in range(t): (a, b) = input().split() a = int(a) b = int(b) print(0.5 + a / (b << 4) if 4 * b > a else 1 - b / a if a else 1)
python
11
0.477124
66
24.5
6
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict mod = 10 ** 9 + 7 mod1 = 998244353 import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) (self.buffer.truncate(0), self.buffer.seek(0)) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda : self.buffer.read().decode('ascii') self.readline = lambda : self.buffer.readline().decode('ascii') (sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout)) input = lambda : sys.stdin.readline().rstrip('\r\n') class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError('Out of ranges') @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n class SegmentTree1: def __init__(self, data, default=0, func=lambda a, b: max(a, b)): self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return 'SegmentTree({0})'.format(self.data) class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return 'SegmentTree({0})'.format(self.data) class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print('Invalid argument to calculate n!') print('n must be non-negative value. But the argument was ' + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print('Invalid argument to calculate n^(-1)') print('n must be non-negative value. But the argument was ' + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print('Invalid argument to calculate (n^(-1))!') print('n must be non-negative value. But the argument was ' + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for (_, x) in sorted(zipped_pairs)] return z def product(l): por = 1 for i in range(len(l)): por *= l[i] return por def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while left <= right: mid = int((right + left) / 2) if arr[mid] < key: count = mid + 1 left = mid + 1 else: right = mid - 1 return count def countdig(n): c = 0 while n > 0: n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else '0' * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 leftGreater = n while l <= r: m = int(l + (r - l) / 2) if arr[m] >= k: leftGreater = m r = m - 1 else: l = m + 1 return n - leftGreater for ik in range(int(input())): (a, b) = map(int, input().split()) if b == 0: print(1) continue elif a == 0: print(0.5) continue if 4 * b >= a: print((a * b + a * a / 8) / (2 * a * b)) else: print((2 * a * b - 2 * b * b) / (2 * a * b))
python
17
0.619926
93
22.762279
509
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
t = int(input()) for i in range(t): (a, b) = [int(i) for i in input().split()] b *= 4 if a == 0 and b == 0: print(1) elif a == 0: print(0.5) else: ans = 0.5 if a > b: ans += (a - b) / a / 2 + b / a / 4 else: ans += a / b / 4 print(ans)
python
15
0.440154
43
16.266667
15
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
T = int(input()) for _ in range(T): (a, b) = map(int, input().split()) if b == 0: print(1) elif a == 0: print(0.5) else: m = 2 * a * b t = 1 / 8 * a * a + a * b if b < a / 4: delta = a / 4 - b base = a * (delta / (delta + b)) t -= 1 / 2 * (delta * base) ans = t / m print(round(ans, 8))
python
15
0.433121
35
18.625
16
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
t = int(input()) while t > 0: (a, b) = map(int, input().split()) if a == 0 and b == 0: print(1) elif a == 0: print(0.5) elif b == 0: print(1) else: ans = a * b + a * a / 8.0 if 4 * b <= a: ans = 2.0 * b * b + (a - 4.0 * b) * b + a * b ans /= 2.0 * a * b print('%.10f' % ans) t -= 1
python
16
0.413115
48
18.0625
16
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
def li(): return list(map(int, input().split(' '))) for _ in range(int(input())): (a, b) = li() if b != 0 and a != 0: s = (max(0, a - 4 * b) + a) / 2 s *= min(a / 4, b) ans = 1 / 2 + s / (2 * a * b) print('{:.8f}'.format(ans)) elif b == 0: print(1) else: print(0.5)
python
14
0.448763
42
20.769231
13
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
t = int(input()) for _ in range(t): (a, b) = map(float, input().split()) if b == 0.0: print(1.0) elif a == 0.0: print(0.5) elif a / 4.0 <= b: print((a + 8.0 * b) / 16.0 / b) else: print(1.0 - b / a)
python
14
0.471698
37
18.272727
11
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
for i in range(int(input())): print('%.8f' % (lambda a, b: 1 if a == 0 == b else a / b / 16 + 1 / 2 if b > a / 4 else 1 - b / a)(*list(map(int, input().split()))[0:2]))
python
19
0.494118
139
84
2
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
import sys lines = int(sys.stdin.readline()) for _ in range(lines): (a, b) = map(float, sys.stdin.readline().split(' ')) if b == 0.0: print(1) elif a <= 4 * b: print((0.125 * a + b) / (2.0 * b)) else: print((a - b) / a)
python
13
0.534783
53
22
10
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
T = int(input()) while T > 0: T -= 1 (a, b) = map(int, input().split()) if a == 0 and b == 0: print(1) elif a == 0: print(0.5) elif b == 0: print(1) else: check1 = a / 4 if check1 <= b: ans = a * b + a * check1 / 2 else: ans = 2 * a * b - 2 * b * b ans = ans / (2 * a * b) print(ans)
python
14
0.448718
35
16.333333
18
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
def f(p, q): if p == 0 and q == 0: return 1 if p == 0: return 0.5 if q == 0: return 1 if q * 4 <= p: return 1 - q * 2 * q / (2 * p * q) else: return 1 - (q - p / 4 + q) * p / (4 * p * q) for i in range(int(input())): (p, q) = map(int, input().split(' ')) print(f(p, q))
python
14
0.442509
46
19.5
14
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you! It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models. Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: <image> Determine the probability with which an aim can be successfully hit by an anvil. You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges. Input The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10. Output Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6. Examples Input 2 4 2 1 2 Output 0.6250000000 0.5312500000
taco
def interpreter(code, iterations, width, height): code = ''.join((c for c in code if c in '[news]*')) canvas = [[0] * width for _ in range(height)] row = col = step = count = loop = 0 while step < len(code) and count < iterations: command = code[step] if loop: if command == '[': loop += 1 elif command == ']': loop -= 1 elif command == 'n': row = (row - 1) % height elif command == 's': row = (row + 1) % height elif command == 'w': col = (col - 1) % width elif command == 'e': col = (col + 1) % width elif command == '*': canvas[row][col] ^= 1 elif command == '[' and canvas[row][col] == 0: loop += 1 elif command == ']' and canvas[row][col] != 0: loop -= 1 step += 1 if not loop else loop // abs(loop) count += 1 if not loop else 0 return '\r\n'.join((''.join(map(str, row)) for row in canvas))
python
13
0.551163
63
29.714286
28
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco
def interpreter(code, iterations, width, height): grid = [[0] * width for _ in range(height)] code = [c for c in code if c in '[]nesw*'] (jumps, stack) = ({}, []) for (i, c) in enumerate(code): if c == '[': stack.append(i) if c == ']': jumps[i] = stack.pop() jumps[jumps[i]] = i (ptr, x, y) = (-1, 0, 0) while iterations > 0 and ptr < len(code) - 1: ptr += 1 iterations -= 1 c = code[ptr] if c == 'n': y = (y - 1) % height if c == 's': y = (y + 1) % height if c == 'w': x = (x - 1) % width if c == 'e': x = (x + 1) % width if c == '*': grid[y][x] = 1 - grid[y][x] if c == '[' and (not grid[y][x]): ptr = jumps[ptr] if c == ']' and grid[y][x]: ptr = jumps[ptr] return '\r\n'.join((''.join(map(str, row)) for row in grid))
python
12
0.480818
61
25.066667
30
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco
from collections import defaultdict def interpreter(code, iterations, w, h): (cp, r, c, p, stk, brackets, grid) = (0, 0, 0, 0, [], {}, [[0] * w for _ in range(h)]) for (i, cc) in enumerate(code): if cc == '[': stk.append(i) elif cc is ']': brackets[i] = stk.pop() brackets[brackets[i]] = i while p < iterations and cp < len(code): if code[cp] == '*': grid[r][c] = 0 if grid[r][c] else 1 elif code[cp] == '[' and grid[r][c] == 0: cp = brackets[cp] elif code[cp] == ']' and grid[r][c] == 1: cp = brackets[cp] elif code[cp] == 'n': r = r - 1 if r else h - 1 elif code[cp] == 'w': c = c - 1 if c else w - 1 elif code[cp] == 's': r = r + 1 if r < h - 1 else 0 elif code[cp] == 'e': c = c + 1 if c < w - 1 else 0 (cp, p) = (cp + 1, p + 1 if code[cp] in '[]nsew*' else p) return '\r\n'.join([''.join((str(e) for e in r)) for r in grid])
python
13
0.511864
87
31.777778
27
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco
def interpreter(code, iterations, width, height): inter = Inter(code, width, height) inter.run(iterations) return '\r\n'.join((''.join(map(str, e)) for e in inter.grid)) class Inter: _instruct = {'w': 'moveW', 'e': 'moveE', 'n': 'moveN', 's': 'moveS', '*': 'flip', '[': 'jumpP', ']': 'jumpB'} _nonC = lambda x: None def __init__(self, code, w, h): self.grid = [[0] * w for e in range(h)] self.com = code (self.w, self.h) = (w, h) (self.x, self.y) = (0, 0) (self.i, self.it) = (0, 0) def countIteration(f): def wrap(cls): cls.it += 1 return f(cls) return wrap def run(self, iterat): while self.it < iterat and self.i < len(self.com): getattr(self, self._instruct.get(self.com[self.i], '_nonC'))() self.i += 1 @countIteration def moveE(self): self.x = (self.x + 1) % self.w @countIteration def moveW(self): self.x = (self.x - 1) % self.w @countIteration def moveN(self): self.y = (self.y - 1) % self.h @countIteration def moveS(self): self.y = (self.y + 1) % self.h @countIteration def flip(self): self.grid[self.y][self.x] = int(not self.grid[self.y][self.x]) @countIteration def jumpP(self): if self.grid[self.y][self.x] == 0: self._jump(1, ']', '[') @countIteration def jumpB(self): if self.grid[self.y][self.x] == 1: self._jump(-1, '[', ']') def _jump(self, way, need, past, nest=0): while way: self.i += way if self.com[self.i] == need and (not nest): break if self.com[self.i] == need and nest: nest -= 1 if self.com[self.i] == past: nest += 1
python
15
0.582157
110
22.253731
67
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco
def pairs(code): opening = [] matching = {} for (i, c) in enumerate(code): if c == '[': opening.append(i) elif c == ']': j = opening.pop() matching[i] = j matching[j] = i assert not opening return matching def interpreter(code, iterations, width, height): matching = pairs(code) x = 0 y = 0 canvas = [[0 for _ in range(width)] for _ in range(height)] index = 0 iterations_done = 0 while iterations_done < iterations: try: c = code[index] except IndexError: break iterations_done += 1 if c == 'n': y -= 1 y %= height index += 1 elif c == 's': y += 1 y %= height index += 1 elif c == 'w': x -= 1 x %= width index += 1 elif c == 'e': x += 1 x %= width index += 1 elif c == '*': canvas[y][x] ^= 1 index += 1 elif c == '[': if canvas[y][x] == 0: index = matching[index] index += 1 elif c == ']': if canvas[y][x] != 0: index = matching[index] index += 1 else: iterations_done -= 1 index += 1 return '\r\n'.join((''.join(map(str, row)) for row in canvas))
python
13
0.531163
63
17.859649
57
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco
def build_jump_table(code): jumps = {} stack = [] for (i, c) in enumerate(code): if c == '[': stack.append(i) elif c == ']': j = stack.pop() jumps[i] = j jumps[j] = i return jumps class Interpreter: def __init__(self, code, width, height): self.code = code self.jumps = build_jump_table(code) self.cells = [[0] * width for _ in range(height)] self.width = width self.height = height self.r = 0 self.c = 0 @property def value(self): return self.cells[self.r][self.c] @value.setter def value(self, val): self.cells[self.r][self.c] = val def run(self, iterations): pc = 0 while pc < len(self.code) and iterations > 0: op = self.code[pc] if op == '*': self.value = 1 - self.value elif op == 'n': self.r = (self.r - 1) % self.height elif op == 's': self.r = (self.r + 1) % self.height elif op == 'w': self.c = (self.c - 1) % self.width elif op == 'e': self.c = (self.c + 1) % self.width elif op == '[' and self.value == 0: pc = self.jumps[pc] elif op == ']' and self.value == 1: pc = self.jumps[pc] pc += 1 iterations -= op in '*nswe[]' return '\r\n'.join((''.join(map(str, row)) for row in self.cells)) def interpreter(code, iterations, width, height): ip = Interpreter(code, width, height) return ip.run(iterations)
python
16
0.577126
68
22.732143
56
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco
class Memory: def __init__(self, width, height): self.__x = 0 self.__y = 0 self.width = width self.height = height self.mem = [[0] * width for _ in range(height)] def flip(self): self.mem[self.y][self.x] = (self.get() + 1) % 2 def get(self): return self.mem[self.y][self.x] def to_string(self): return '\r\n'.join((''.join(map(str, row)) for row in self.mem)) @property def x(self): return self.__x @x.setter def x(self, val): self.__x = val % self.width @property def y(self): return self.__y @y.setter def y(self, val): self.__y = val % self.height def interpreter(code, iterations, width, height): op_ptr = 0 mem = Memory(width, height) jumps = {} bracket = [] for (i, op) in enumerate(code): if op == '[': bracket.append(i) elif op == ']': jumps[bracket[-1]] = i jumps[i] = bracket.pop() while iterations and op_ptr < len(code): op = code[op_ptr] if op in 'nesw*[]': iterations -= 1 if op == 'n': mem.y -= 1 elif op == 'e': mem.x += 1 elif op == 's': mem.y += 1 elif op == 'w': mem.x -= 1 elif op == '*': mem.flip() elif op == '[' and mem.get() == 0: op_ptr = jumps[op_ptr] elif op == ']' and mem.get() != 0: op_ptr = jumps[op_ptr] op_ptr += 1 return mem.to_string()
python
13
0.55625
66
18.692308
65
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. ## The Language Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape. Valid commands in Paintfuck include: - `n` - Move data pointer north (up) - `e` - Move data pointer east (right) - `s` - Move data pointer south (down) - `w` - Move data pointer west (left) - `*` - Flip the bit at the current cell (same as in Smallfuck) - `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck) - `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck) The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task). In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape. Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine. More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck). ## The Task Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order: 1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid. 2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid. 3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer. 4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer. A few things to note: - Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters - Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid - In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid. - One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.** - Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`). - Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument. - The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is ``` [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ] ``` ... then your return string should be `"100\r\n010\r\n001"`. Good luck :D ## Kata in this Series 1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck) 2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter) 3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter** 4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter)
taco