0% found this document useful (0 votes)
9 views43 pages

Test4 200

The document contains multiple code snippets in Python and C/C++ that implement various algorithms such as searching in rotated sorted arrays, finding the length of the longest substring without repeating characters, generating Gray codes, and finding palindromes. Each code snippet is accompanied by a main function that handles input and output for the respective algorithm. The document showcases a variety of programming challenges and their solutions.

Uploaded by

jayendrarathod07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views43 pages

Test4 200

The document contains multiple code snippets in Python and C/C++ that implement various algorithms such as searching in rotated sorted arrays, finding the length of the longest substring without repeating characters, generating Gray codes, and finding palindromes. Each code snippet is accompanied by a main function that handles input and output for the respective algorithm. The document showcases a variety of programming challenges and their solutions.

Uploaded by

jayendrarathod07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Q1

from typing import List

class Solution:

def search(self, nums: List[int], target: int) -> int:

left, right = 0, len(nums) - 1

while left <= right:

mid = (left + right) // 2

if nums[mid] == target:

return mid

# Left half is sorted

if nums[left] <= nums[mid]:

if nums[left] <= target < nums[mid]:

right = mid - 1

else:

left = mid + 1

# Right half is sorted

else:

if nums[mid] < target <= nums[right]:

left = mid + 1

else:

right = mid - 1

return -1
# Runtime input

if __name__ == "__main__":

# Take the input for the rotated sorted array

nums = list(map(int, input().split()))

target = int(input())

# Create Solution object and search

solution = Solution()

result = solution.search(nums, target)

# Print the result

print(result)

Q2

#include <stdio.h>

#include <string.h>

#include <stdbool.h>

int lengthOfLongestSubstring(char* s) {

int n = strlen(s);

int maxLength = 0;

int left = 0;

bool charSet[256] = {0}; // ASCII character set

for (int right = 0; right < n; right++) {

while (charSet[s[right]]) {

charSet[s[left]] = false;

left++;

}
charSet[s[right]] = true;

maxLength = (right - left + 1) > maxLength ? (right - left + 1) : maxLength;

return maxLength;

int main() {

char s[1000];

fgets(s, sizeof(s), stdin);

s[strcspn(s, "\n")] = 0; // Remove newline character

printf("%d\n", lengthOfLongestSubstring(s));

return 0;

Q3

#include <stdio.h>

#include <stdlib.h>

int* grayCode(int n, int* returnSize) {

*returnSize = 1 << n;

int* result = (int*)malloc(*returnSize * sizeof(int));

result[0] = 0;

for (int i = 1; i < *returnSize; i++) {

result[i] = i ^ (i >> 1);

}
return result;

void printArray(int* arr, int size) {

for (int i = 0; i < size; i++) {

printf("%d ", arr[i]);

printf("\n");

int main() {

int n;

scanf("%d", &n); // Input: value for n

int returnSize;

int* result = grayCode(n, &returnSize);

printArray(result, returnSize);

free(result); // Free the allocated memory

return 0;

Q4

#include <stdio.h>

#include <string.h>

int expand(const char *s, int left, int right) {

while (left >= 0 && right < strlen(s) && s[left] == s[right]) {
left--;

right++;

return right - left - 1;

void longestPalindrome(const char *s, char *result) {

int start = 0, end = 0, maxLen = 0;

for (int i = 0; i < strlen(s); i++) {

int len1 = expand(s, i, i);

int len2 = expand(s, i, i + 1);

int currentMax = len1 > len2 ? len1 : len2;

int newStart = i - (currentMax - 1) / 2;

int newEnd = i + currentMax / 2;

if (currentMax > maxLen || (currentMax == maxLen && newStart < start)) {

maxLen = currentMax;

start = newStart;

end = newEnd;

strncpy(result, s + start, end - start + 1);

result[end - start + 1] = '\0';

}
int main() {

char s[1001], result[1001];

scanf("%s", s);

longestPalindrome(s, result);

printf("%s\n", result);

return 0;

Q5

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <stdbool.h>

#include <ctype.h>

bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {

int rows = matrixSize;

int cols = matrixColSize[0];

int i = 0;

int j = cols - 1;

while (i < rows && j >= 0) {

if (matrix[i][j] == target) {

return true;

} else if (matrix[i][j] > target) {

j--;

} else {

i++;

}
return false;

// Function to count rows in the input string

int countRows(const char* str) {

int count = 0;

int depth = 0;

for (int i = 0; str[i] != '\0'; i++) {

if (str[i] == '[') {

depth++;

if (depth == 2) count++;

} else if (str[i] == ']') {

depth--;

return count;

// Function to count columns in the first row

int countCols(const char* str) {

int count = 1; // At least one column

int depth = 0;

bool inFirstRow = false;

for (int i = 0; str[i] != '\0'; i++) {

if (str[i] == '[') {
depth++;

if (depth == 2) inFirstRow = true;

} else if (str[i] == ']') {

if (depth == 2 && inFirstRow) break;

depth--;

} else if (str[i] == ',' && inFirstRow && depth == 2) {

count++;

return count;

// Parse a number from a string, advancing the pointer

int parseNumber(char** p) {

while (**p && !isdigit(**p) && **p != '-') (*p)++;

int sign = 1;

if (**p == '-') {

sign = -1;

(*p)++;

int num = 0;

while (isdigit(**p)) {

num = num * 10 + (**p - '0');

(*p)++;

return num * sign;

}
int** parseMatrix(char* input, int* rows, int* cols) {

// Count rows and columns

*rows = countRows(input);

*cols = countCols(input);

// Allocate matrix

int** matrix = (int**)malloc(*rows * sizeof(int*));

for (int i = 0; i < *rows; i++) {

matrix[i] = (int*)malloc(*cols * sizeof(int));

// Parse numbers

char* p = input;

int row = 0, col = 0;

// Skip to the first number

while (*p && *p != '[') p++;

p++; // Skip the outer '['

while (*p) {

if (*p == '[') {

p++; // Skip the inner '['

col = 0;

while (*p && *p != ']') {

if (isdigit(*p) || *p == '-') {

matrix[row][col] = parseNumber(&p);
col++;

} else {

p++;

row++; // Next row

} else {

p++;

if (row >= *rows) break;

return matrix;

void freeMatrix(int** matrix, int rows) {

for (int i = 0; i < rows; i++) {

free(matrix[i]);

free(matrix);

int main() {

char input[1000];

int target;
// Read matrix input

fgets(input, sizeof(input), stdin);

// Read target value

scanf("%d", &target);

int rows, cols;

int** matrix = parseMatrix(input, &rows, &cols);

int* colSizes = (int*)malloc(rows * sizeof(int));

for (int i = 0; i < rows; i++) {

colSizes[i] = cols;

bool result = searchMatrix(matrix, rows, colSizes, target);

printf("%s\n", result ? "true" : "false");

freeMatrix(matrix, rows);

free(colSizes);

return 0;

Q6

#include <stdio.h>

#include <stdlib.h>

#include <string.h>
char* convert(const char* s, int numRows) {

int len = strlen(s);

if (numRows == 1 || numRows >= len) return strdup(s);

char** rows = (char**)malloc(numRows * sizeof(char*));

int* sizes = (int*)calloc(numRows, sizeof(int));

for (int i = 0; i < numRows; i++) {

rows[i] = (char*)malloc((len + 1) * sizeof(char));

rows[i][0] = '\0';

int idx = 0, dir = 1;

for (int i = 0; i < len; i++) {

int l = sizes[idx];

rows[idx][l] = s[i];

rows[idx][l + 1] = '\0';

sizes[idx]++;

if (idx == 0) dir = 1;

else if (idx == numRows - 1) dir = -1;

idx += dir;

char* result = (char*)malloc((len + 1) * sizeof(char));

result[0] = '\0';

for (int i = 0; i < numRows; i++) {

strcat(result, rows[i]);

free(rows[i]);

}
free(rows);

free(sizes);

return result;

int main() {

char s[1001];

int numRows;

scanf("%s", s);

scanf("%d", &numRows);

char* res = convert(s, numRows);

printf("%s\n", res);

free(res);

return 0;

Q7

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

char* convert(const char* s, int numRows) {

int len = strlen(s);

if (numRows == 1 || numRows >= len) return strdup(s);

char** rows = (char**)malloc(numRows * sizeof(char*));

int* sizes = (int*)calloc(numRows, sizeof(int));

for (int i = 0; i < numRows; i++) {


rows[i] = (char*)malloc((len + 1) * sizeof(char));

rows[i][0] = '\0';

int idx = 0, dir = 1;

for (int i = 0; i < len; i++) {

int l = sizes[idx];

rows[idx][l] = s[i];

rows[idx][l + 1] = '\0';

sizes[idx]++;

if (idx == 0) dir = 1;

else if (idx == numRows - 1) dir = -1;

idx += dir;

char* result = (char*)malloc((len + 1) * sizeof(char));

result[0] = '\0';

for (int i = 0; i < numRows; i++) {

strcat(result, rows[i]);

free(rows[i]);

free(rows);

free(sizes);

return result;

int main() {
char s[1001];

int numRows;

scanf("%s", s);

scanf("%d", &numRows);

char* res = convert(s, numRows);

printf("%s\n", res);

free(res);

return 0;

Q8

#include <stdio.h>

#include <stdlib.h>

int compare(const void* a, const void* b) {

return (*(int*)a - *(int*)b);

void fourSum(int* nums, int n, int target) {

qsort(nums, n, sizeof(int), compare);

for (int i = 0; i < n - 3; i++) {

if (i > 0 && nums[i] == nums[i - 1]) continue;

for (int j = i + 1; j < n - 2; j++) {

if (j > i + 1 && nums[j] == nums[j - 1]) continue;

int left = j + 1;

int right = n - 1;
while (left < right) {

long long sum = (long long)nums[i] + nums[j] + nums[left] + nums[right];

if (sum == target) {

printf("[%d, %d, %d, %d]\n", nums[i], nums[j], nums[left], nums[right]);

while (left < right && nums[left] == nums[left + 1]) left++;

while (left < right && nums[right] == nums[right - 1]) right--;

left++;

right--;

} else if (sum < target) {

left++;

} else {

right--;

int main() {

int nums[1000], n = 0, target;

char c;

while (scanf("%d", &nums[n]) == 1) {

n++;
c = getchar();

if (c == '\n' || c == EOF) break;

scanf("%d", &target);

fourSum(nums, n, target);

return 0;

Q9

#include <stdio.h>

#include <limits.h>

#include <ctype.h>

int myAtoi(char* s) {

int sign = 1, i = 0;

long res = 0;

// Skip leading whitespaces

while (s[i] == ' ') {

i++;

// Handle sign

if (s[i] == '-') {

sign = -1;

i++;
} else if (s[i] == '+') {

i++;

// Process numerical characters

while (s[i] != '\0' && isdigit(s[i])) {

res = res * 10 + (s[i] - '0'); // Convert char to number

// Check for overflow

if (sign * res > INT_MAX) return INT_MAX;

if (sign * res < INT_MIN) return INT_MIN;

i++;

return sign * res;

int main() {

char s[100];

fgets(s, sizeof(s), stdin);

printf("%d\n", myAtoi(s));

return 0;

Q10

#include <stdio.h>

int binarySearch(int nums[], int size, int target, int findStart) {


int left = 0, right = size - 1;

int result = -1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (nums[mid] == target) {

result = mid;

// To find the start or end, adjust the search space accordingly

if (findStart) {

right = mid - 1; // Search the left half for the first occurrence

} else {

left = mid + 1; // Search the right half for the last occurrence

} else if (nums[mid] < target) {

left = mid + 1;

} else {

right = mid - 1;

return result;

void searchRange(int nums[], int size, int target) {

// Binary search for the leftmost index (starting position)

int start = binarySearch(nums, size, target, 1);


// If target is not found, return [-1, -1]

if (start == -1) {

printf("[-1, -1]\n");

return;

// Binary search for the rightmost index (ending position)

int end = binarySearch(nums, size, target, 0);

// Print the result

printf("[%d, %d]\n", start, end);

int main() {

int nums[1000], target, n = 0;

// Take input for the sorted array

while (scanf("%d", &nums[n]) == 1) {

n++;

if (getchar() == '\n') {

break;

// Take the target value

scanf("%d", &target);

// Search for the range


searchRange(nums, n, target);

return 0;

Q11

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

class Solution {

public:

vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {

vector<vector<int>> graph(n);

vector<vector<int>> result;

vector<int> disc(n, -1), low(n, -1), parent(n, -1);

int time = 0;

// Build the graph

for (auto& connection : connections) {

graph[connection[0]].push_back(connection[1]);

graph[connection[1]].push_back(connection[0]);

// Perform DFS and find bridges

dfs(0, graph, disc, low, parent, time, result);


return result;

private:

void dfs(int u, vector<vector<int>>& graph, vector<int>& disc, vector<int>& low,


vector<int>& parent, int& time, vector<vector<int>>& result) {

disc[u] = low[u] = time++;

for (int v : graph[u]) {

if (disc[v] == -1) { // If 'v' is not visited

parent[v] = u;

dfs(v, graph, disc, low, parent, time, result);

// Check if the subtree rooted at v has a connection back to one of the ancestors of
u

low[u] = min(low[u], low[v]);

// If the lowest vertex reachable from v is after u in DFS, then (u, v) is a bridge

if (low[v] > disc[u]) {

result.push_back({u, v});

} else if (v != parent[u]) { // If 'v' is already visited and is not parent of u

low[u] = min(low[u], disc[v]);

};

int main() {
Solution sol;

int n, m;

cin >> n;

cin >> m;

vector<vector<int>> connections(m);

for (int i = 0; i < m; i++) {

int u, v;

cin >> u >> v;

connections[i] = {u, v};

vector<vector<int>> result = sol.criticalConnections(n, connections);

if (result.empty()) {

cout << "-1" << endl;

} else {

cout << "Critical Connections are:" << endl;

for (const auto& conn : result) {

cout << "[" << conn[0] << ", " << conn[1] << "]" << endl;

return 0;

Q12
#include <iostream>

#include <vector>

#include <unordered_set>

using namespace std;

// GCD

long long gcd(long long a, long long b) {

while (b) {

long long t = b;

b = a % b;

a = t;

return a;

// LCM

long long lcm(long long a, long long b) {

return (a / gcd(a, b)) * b;

// DSU (Union-Find)

class DSU {

vector<int> parent;

public:

DSU(int n) {

parent.resize(n);

for (int i = 0; i < n; i++) parent[i] = i;

}
int find(int v) {

if (parent[v] != v)

parent[v] = find(parent[v]);

return parent[v];

void unite(int a, int b) {

int pa = find(a);

int pb = find(b);

if (pa != pb)

parent[pb] = pa;

int countUniqueRoots() {

unordered_set<int> roots;

for (int i = 0; i < parent.size(); i++)

roots.insert(find(i));

return roots.size();

};

int main() {

int n, threshold;

cin >> n >> threshold;

vector<int> nums(n);

for (int i = 0; i < n; i++)


cin >> nums[i];

DSU dsu(n);

for (int i = 0; i < n; i++) {

for (int j = i + 1; j < n; j++) {

long long l = lcm(nums[i], nums[j]);

if (l <= threshold)

dsu.unite(i, j);

cout << dsu.countUniqueRoots() << endl;

return 0;

Q13

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_N 50

int dirs[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}};

int grid[MAX_N][MAX_N];

int visited[MAX_N][MAX_N];

int area[MAX_N * MAX_N];

int n;
// DFS to label island and calculate its area

int dfs(int i, int j, int index) {

if (i < 0 || i >= n || j < 0 || j >= n || grid[i][j] != 1)

return 0;

grid[i][j] = index;

int a = 1;

for (int d = 0; d < 4; ++d) {

int ni = i + dirs[d][0];

int nj = j + dirs[d][1];

a += dfs(ni, nj, index);

return a;

int max(int a, int b) {

return a > b ? a : b;

int main() {

scanf("%d", &n);

for (int i = 0; i < n; ++i)

for (int j = 0; j < n; ++j)

scanf("%d", &grid[i][j]);

int index = 2;

memset(area, 0, sizeof(area));

// Step 1: Label islands and compute area


for (int i = 0; i < n; ++i)

for (int j = 0; j < n; ++j)

if (grid[i][j] == 1)

area[index++] = dfs(i, j, index);

int max_area = 0;

for (int i = 2; i < index; ++i)

max_area = max(max_area, area[i]);

// Step 2: Try flipping each 0

for (int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) {

if (grid[i][j] == 0) {

int seen[4 * MAX_N] = {0};

int new_area = 1;

for (int d = 0; d < 4; ++d) {

int ni = i + dirs[d][0];

int nj = j + dirs[d][1];

if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] > 1) {

int idx = grid[ni][nj];

if (!seen[idx]) {

new_area += area[idx];

seen[idx] = 1;

}
max_area = max(max_area, new_area);

printf("%d\n", max_area == 0 ? n * n : max_area);

return 0;

Q14

#include <iostream>

#include <vector>

#include <unordered_map>

#include <algorithm>

using namespace std;

class Solution {

public:

int longestCycle(vector<int>& edges) {

int n = edges.size();

vector<int> visited(n, 0); // 0 = not visited, 1 = visiting, 2 = visited

int longest = -1;

for (int i = 0; i < n; i++) {

if (visited[i] != 0) continue;

int current = i;

unordered_map<int, int> nodeIndex; // node -> step index in current DFS


int step = 0;

while (current != -1) {

if (visited[current] == 2) break;

if (visited[current] == 1) {

longest = max(longest, step - nodeIndex[current]);

break;

visited[current] = 1;

nodeIndex[current] = step++;

current = edges[current];

current = i;

while (current != -1 && visited[current] == 1) {

visited[current] = 2;

current = edges[current];

return longest;

};

int main() {

int n;

cin >> n;

vector<int> edges(n);
for (int i = 0; i < n; i++) {

cin >> edges[i];

Solution sol;

cout << sol.longestCycle(edges) << "\n";

return 0;

Q15

#include <stdio.h>

#include <stdlib.h>

int max(int a, int b) { return a > b ? a : b; }

// Helper function to compare subsequences starting at given indices

int compare(int* nums1, int i, int n1, int* nums2, int j, int n2) {

while (i < n1 && j < n2) {

if (nums1[i] != nums2[j])

return nums1[i] - nums2[j];

i++;

j++;

return (n1 - i) - (n2 - j);

// Get max subsequence of length k from nums

int* maxSubsequence(int* nums, int n, int k) {


int* stack = (int*)malloc(k * sizeof(int));

int top = -1;

int drop = n - k;

for (int i = 0; i < n; i++) {

while (top >= 0 && drop > 0 && stack[top] < nums[i]) {

top--;

drop--;

if (top + 1 < k) {

stack[++top] = nums[i];

} else {

drop--;

return stack;

// Merge two subsequences to form max number

int* merge(int* nums1, int n1, int* nums2, int n2, int k) {

int* result = (int*)malloc(k * sizeof(int));

int i = 0, j = 0, r = 0;

while (r < k) {

if (compare(nums1, i, n1, nums2, j, n2) > 0)

result[r++] = nums1[i++];

else

result[r++] = nums2[j++];

return result;
}

int main() {

int m, n, k;

scanf("%d", &m);

int* nums1 = (int*)malloc(m * sizeof(int));

for (int i = 0; i < m; i++) scanf("%d", &nums1[i]);

scanf("%d", &n);

int* nums2 = (int*)malloc(n * sizeof(int));

for (int i = 0; i < n; i++) scanf("%d", &nums2[i]);

scanf("%d", &k);

int start = (k > n) ? k - n : 0;

int end = (k < m) ? k : m;

int* maxRes = (int*)malloc(k * sizeof(int));

for (int i = 0; i < k; i++) maxRes[i] = 0;

for (int i = start; i <= end; i++) {

int len1 = i, len2 = k - i;

int* sub1 = maxSubsequence(nums1, m, len1);

int* sub2 = maxSubsequence(nums2, n, len2);

int* candidate = merge(sub1, len1, sub2, len2, k);

// Compare candidate with maxRes lex order

int flag = 0;

for (int c = 0; c < k; c++) {

if (candidate[c] > maxRes[c]) {


flag = 1;

break;

} else if (candidate[c] < maxRes[c]) {

break;

if (flag) {

for (int c = 0; c < k; c++) maxRes[c] = candidate[c];

free(sub1);

free(sub2);

free(candidate);

for (int i = 0; i < k; i++) {

printf("%d", maxRes[i]);

if (i < k - 1) printf(" ");

printf("\n");

free(nums1);

free(nums2);

free(maxRes);

return 0;

Q16

#include <stdio.h>
// Function to find the minimum element using linear search

int findMin(int* nums, int numsSize) {

int min = nums[0];

for (int i = 1; i < numsSize; i++) {

if (nums[i] < min) {

min = nums[i];

return min;

int main() {

int n;

// Read the number of elements

scanf("%d", &n);

int nums[n];

// Read the array elements

for (int i = 0; i < n; i++) {

scanf("%d", &nums[i]);

// Find and print the minimum element

int result = findMin(nums, n);

printf("Minimum element is: %d\n", result);


return 0;

Q17

#include <stdio.h>

#include <stdlib.h>

int max(int a, int b) {

return (a > b) ? a : b;

int calculateMinimumHP(int** dungeon, int m, int n) {

// Create DP table with (m+1) x (n+1), initialized to a large number

int** dp = (int**)malloc((m + 1) * sizeof(int*));

for (int i = 0; i <= m; i++) {

dp[i] = (int*)malloc((n + 1) * sizeof(int));

for (int j = 0; j <= n; j++) {

dp[i][j] = 1000000000; // large number as infinity substitute

// Set the virtual cells beyond the princess cell to 1

dp[m][n - 1] = 1;

dp[m - 1][n] = 1;

// Fill dp table from bottom-right to top-left

for (int i = m - 1; i >= 0; i--) {

for (int j = n - 1; j >= 0; j--) {

int min_health_on_exit = (dp[i + 1][j] < dp[i][j + 1]) ? dp[i + 1][j] : dp[i][j + 1];
dp[i][j] = max(1, min_health_on_exit - dungeon[i][j]);

int result = dp[0][0];

// Free dp memory

for (int i = 0; i <= m; i++) {

free(dp[i]);

free(dp);

return result;

int main() {

int m, n;

scanf("%d %d", &m, &n);

int** dungeon = (int**)malloc(m * sizeof(int*));

for (int i = 0; i < m; i++) {

dungeon[i] = (int*)malloc(n * sizeof(int));

for (int j = 0; j < n; j++) {

scanf("%d", &dungeon[i][j]);

int result = calculateMinimumHP(dungeon, m, n);


printf("%d\n", result);

for (int i = 0; i < m; i++) {

free(dungeon[i]);

free(dungeon);

return 0;

Q18

#include <stdio.h>

#define MAX 100

int max(int a, int b) {

return (a > b) ? a : b;

int findMaxProfit(int price[], int n, int k) {

if (n <= 1) {

return 0;

int profit[k + 1][n];

for (int i = 0; i <= k; i++) {

for (int j = 0; j < n; j++) {

if (i == 0 || j == 0) {

profit[i][j] = 0;

} else {
int max_so_far = 0;

for (int x = 0; x < j; x++) {

int curr_price = price[j] - price[x] + profit[i-1][x];

if (max_so_far < curr_price) {

max_so_far = curr_price;

profit[i][j] = max(profit[i][j-1], max_so_far);

return profit[k][n-1];

int main() {

int n, k, price[MAX];

scanf("%d", &n);

for (int i = 0; i < n; i++) {

scanf("%d", &price[i]);

scanf("%d", &k);

printf("%d\n", findMaxProfit(price, n, k));

return 0;

Q19

#include <stdio.h>

#include <stdlib.h>

#include <string.h> // Required for strchr and strtok


// Function to remove duplicates from a sorted array

int removeDuplicates(int* nums, int numsSize) {

if (numsSize == 0) return 0;

int j = 1;

for (int i = 1; i < numsSize; i++) {

if (nums[i] != nums[i - 1]) {

nums[j] = nums[i];

j++;

return j;

int main() {

char input[1000];

// Read input string

fgets(input, sizeof(input), stdin);

// Remove the brackets from the input string

char *start = strchr(input, '[') + 1;

char *end = strchr(input, ']');

*end = '\0'; // Terminate the string at the closing bracket

// Split the input into integers using strtok

int nums[100];
int i = 0;

char* token = strtok(start, ",");

while (token != NULL) {

nums[i++] = atoi(token); // Convert string to integer

token = strtok(NULL, ",");

int length = removeDuplicates(nums, i);

// Print the result

printf("%d, nums = [", length);

for (int j = 0; j < length; j++) {

printf("%d", nums[j]);

if (j < length - 1) {

printf(", ");

printf("]\n");

return 0;

Q20

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int removeElement(int* nums, int numsSize, int val) {


int index = 0;

for (int i = 0; i < numsSize; i++) {

if (nums[i] != val) {

nums[index] = nums[i];

index++;

return index;

int main() {

char input[1000];

fgets(input, sizeof(input), stdin); // Read the array input

// Remove the square brackets and split the string by commas

char* start = strchr(input, '[') + 1;

char* end = strchr(input, ']');

*end = '\0'; // Replace ']' with '\0' to terminate the string

int nums[100];

int n = 0;

char* token = strtok(start, ",");

while (token != NULL) {

nums[n++] = atoi(token); // Convert string to integer and add to nums array

token = strtok(NULL, ",");

int val;
scanf("%d", &val); // Read the value to be removed

int length = removeElement(nums, n, val);

// Print the result

printf("%d, nums = [", length);

for (int i = 0; i < length; i++) {

printf("%d", nums[i]);

if (i < length - 1) {

printf(", ");

printf("]\n");

return 0;

You might also like