In this tutorial, we will discuss the fundamental concepts and solve two common programming problems:
- Checking if a sequence of characters is binary.
- Counting the number of elements less than or equal to a given element in an array.
Problem 1: Check if Sequence is Binary
Problem Statement: Given a non-empty sequence of characters str
, return true
if the sequence is binary (contains only ‘0’ and ‘1’), else return false
.
Approach: To solve this problem, we need to iterate through the given string and check if each character is either ‘0’ or ‘1’. If we encounter any character that is not ‘0’ or ‘1’, we return false
. If we successfully check all characters and they are all ‘0’ or ‘1’, we return true
.
Solution in Python:
def is_binary_sequence(s):
for char in s:
if char not in '01':
return False
return True
# Example usage:
print(is_binary_sequence("101010")) # Output: True
print(is_binary_sequence("102010")) # Output: False
Solution in C++:
#include <iostream>
#include <string>
using namespace std;
bool isBinarySequence(const string& s) {
for (char c : s) {
if (c != '0' && c != '1') {
return false;
}
}
return true;
}
int main() {
cout << isBinarySequence("101010") << endl; // Output: 1 (true)
cout << isBinarySequence("102010") << endl; // Output: 0 (false)
return 0;
}
Problem 2: Count of Smaller Elements
Problem Statement: Given an unsorted array arr
and a value x
, find the count of elements in the array that are less than or equal to x
.
Approach: To solve this problem, we iterate through the array and count the elements that are less than or equal to x
. This approach ensures a time complexity of O(n) and an auxiliary space of O(1).
Solution in Python:
def count_smaller_or_equal(arr, x):
count = 0
for num in arr:
if num <= x:
count += 1
return count
# Example usage:
arr1 = [1, 2, 4, 5, 8, 10]
x1 = 9
print(count_smaller_or_equal(arr1, x1)) # Output: 5
arr2 = [1, 2, 2, 2, 5, 7, 9]
x2 = 2
print(count_smaller_or_equal(arr2, x2)) # Output: 4
Solution in C++:
#include <iostream>
#include <vector>
using namespace std;
int countSmallerOrEqual(const vector<int>& arr, int x) {
int count = 0;
for (int num : arr) {
if (num <= x) {
count += 1;
}
}
return count;
}
int main() {
vector<int> arr1 = {1, 2, 4, 5, 8, 10};
int x1 = 9;
cout << countSmallerOrEqual(arr1, x1) << endl; // Output: 5
vector<int> arr2 = {1, 2, 2, 2, 5, 7, 9};
int x2 = 2;
cout << countSmallerOrEqual(arr2, x2) << endl; // Output: 4
return 0;
}
Conclusion
In this tutorial, we covered the fundamental concepts of two common programming problems. We learned how to:
- Check if a sequence of characters is binary using simple iteration.
- Count the number of elements less than or equal to a given value in an array with a straightforward loop.
By solving these problems in both Python and C++, we highlighted the importance of understanding basic iteration and conditional checking, which are crucial for tackling a wide range of programming challenges.