You are on page 1of 15

1.

reverse words in a string:write a program to reverse the words in a given string without
using any library function example hello world output world hello

#include <stdio.h>

void reverseWords(char* str) {


// Reversing the entire string
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}

// Reversing each word in the string


int wordStart = 0;
int wordEnd = 0;
while (str[wordEnd] != '\0') {
if (str[wordEnd] == ' ') {
int wordLen = wordEnd - wordStart;
for (int i = 0; i < wordLen / 2; i++) {
char temp = str[wordStart + i];
str[wordStart + i] = str[wordEnd - i - 1];
str[wordEnd - i - 1] = temp;
}
wordStart = wordEnd + 1;
}
wordEnd++;
}

// Reversing the last word in the string


int lastWordLen = wordEnd - wordStart;
for (int i = 0; i < lastWordLen / 2; i++) {
char temp = str[wordStart + i];
str[wordStart + i] = str[wordEnd - i - 1];
str[wordEnd - i - 1] = temp;
}
}

int main() {
char str[100];

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

// Removing the trailing newline character


str[strlen(str) - 1] = '\0';

reverseWords(str);

printf("Reversed string: %s\n", str);

return 0;
}
```
Input:hello world
Output:world hello

2.longest increasing subarray with sum k:given an array of integers and a target sum k,find
the length of longest subarray with a sum equal to k the elements of the array can be both
positive and negative

```c
#include <stdio.h>

int longestSubarrayWithSumK(int arr[], int size, int k) {


int maxLength = 0;
int sum = 0;
int startIndex = -1;
int endIndex = -1;
int prefixSum[size];

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


sum += arr[i];
prefixSum[i] = sum;

if (sum == k) {
maxLength = i + 1;
startIndex = 0;
endIndex = i;
}

int target = sum - k;


for (int j = 0; j < i; j++) {
if (prefixSum[j] == target) {
int length = i - j;
if (length > maxLength) {
maxLength = length;
startIndex = j + 1;
endIndex = i;
}
}
}
}

printf("Longest subarray with sum %d: ", k);


for (int i = startIndex; i <= endIndex; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return maxLength;
}

int main() {
int arr[] = { 3, 1, 2, -2, 4, 2, -1, 0, -3, 1 };
int size = sizeof(arr) / sizeof(arr[0]);
int k = 4;

int length = longestSubarrayWithSumK(arr, size, k);

printf("Length of the longest subarray: %d\n", length);

return 0;
}

Input: arr[] = { 10, 5, 2, 7, 1, 9 }, k = 15


Output: 4
Explanation: The sub-array is {5, 2, 7, 1}.

Input: arr[] = {-5, 8, -14, 2, 4, 12}, k = -5


Output: 5

3.matrix spiral transversal :given an N×M matrix ,print its elements in spiral order for
example given the following 3×3 matrix

```c
#include <stdio.h>

void spiralOrder(int matrix[][3], int rows, int columns) {


int topRow = 0;
int bottomRow = rows - 1;
int leftColumn = 0;
int rightColumn = columns - 1;

while (topRow <= bottomRow && leftColumn <= rightColumn) {


// Print top row
for (int i = leftColumn; i <= rightColumn; i++) {
printf("%d ", matrix[topRow][i]);
}
topRow++;

// Print right column


for (int i = topRow; i <= bottomRow; i++) {
printf("%d ", matrix[i][rightColumn]);
}
rightColumn--;

// Print bottom row


if (topRow <= bottomRow) {
for (int i = rightColumn; i >= leftColumn; i--) {
printf("%d ", matrix[bottomRow][i]);
}
bottomRow--;
}

// Print left column


if (leftColumn <= rightColumn) {
for (int i = bottomRow; i >= topRow; i--) {
printf("%d ", matrix[i][leftColumn]);
}
leftColumn++;
}
}
}

int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int rows = sizeof(matrix) / sizeof(matrix[0]);


int columns = sizeof(matrix[0]) / sizeof(matrix[0][0]);

spiralOrder(matrix, rows, columns);

return 0;
}
Input: {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16 }}
Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Explanation: The output is matrix in spiral format.
4.counting inversions:given a array of integers,find the Number of inversions in the array an
inversions occurs when two elements in the array are out of their natural order
for example in the array [2,4,1,3,5],there are three inversions:(2,1),(4,1),(4,3)

```c
#include <stdio.h>

int merge(int arr[], int temp[], int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = left;
int invCount = 0;

while (i <= mid && j <= right) {


if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
invCount += (mid - i + 1);
}
}

while (i <= mid) {


temp[k++] = arr[i++];
}

while (j <= right) {


temp[k++] = arr[j++];
}

for (int m = left; m <= right; m++) {


arr[m] = temp[m];
}

return invCount;
}

int mergeSort(int arr[], int temp[], int left, int right) {


int invCount = 0;

if (left < right) {


int mid = (left + right) / 2;

invCount += mergeSort(arr, temp, left, mid);


invCount += mergeSort(arr, temp, mid + 1, right);

invCount += merge(arr, temp, left, mid, right);


}

return invCount;
}

int countInversions(int arr[], int n) {


int temp[n];
return mergeSort(arr, temp, 0, n - 1);
}

int main() {
int arr[] = {2, 4, 1, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);

int inversions = countInversions(arr, n);

printf("Number of inversions: %d\n", inversions);

return 0;
}
```
Input: arr[] = {8, 4, 2, 1}
Output: 6
Explanation: Given array has six inversions: (8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1).

Input: arr[] = {1, 20, 6, 4, 5}


Output: 5
Explanation: Given array has five inversions: (20, 6), (20, 4), (20, 5), (6, 4), (6, 5).

5.maximum sum subarray:given an array of integers,find the maximum possible sum of a


contiguous subarray when the array can be treated as a circular array.for example in the
array [5,-3,5],the maximum sum is 10(5+5), considering the circular property in c program

```c
#include <stdio.h>

int maxSubarraySum(int arr[], int n) {


int maxSum = arr[0], currMax = arr[0];
int minSum = arr[0], currMin = arr[0];
int totalSum = arr[0];

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


currMax = (currMax + arr[i] > arr[i]) ? currMax + arr[i] : arr[i];
maxSum = (currMax > maxSum) ? currMax : maxSum;

currMin = (currMin + arr[i] < arr[i]) ? currMin + arr[i] : arr[i];


minSum = (currMin < minSum) ? currMin : minSum;

totalSum += arr[i];
}

return (maxSum > totalSum - minSum) ? maxSum : totalSum - minSum;


}

int main() {
int arr[] = {5, -3, 5};
int n = sizeof(arr) / sizeof(arr[0]);

int maxSum = maxSubarraySum(arr, n);


printf("Maximum sum of a contiguous subarray: %d\n", maxSum);

return 0;
}
```
Input: arr[] = {8, -8, 9, -9, 10, -11, 12}
Output: 22
Explanation: Subarray 12, 8, -8, 9, -9, 10 gives the maximum sum, that is 22.

Input: arr[] = {10, -3, -4, 7, 6, 5, -4, -1}


Output: 23
Explanation: Subarray 7, 6, 5, -4, -1, 10 gives the maximum sum, that is 23.

6.Longest Common Subsequence: Given two sequences, find the length of the longest
common subsequence (LCS). A subsequence is a sequence that appears in the same
relative order but not necessarily contiguous. For example, the LCS of "ABCD" and "ACDF"
is "ACD" with a length of 3.

```c
#include <stdio.h>
#include <string.h>

int max(int a, int b) {


return (a > b) ? a : b;
}

int lcsLength(char* sequence1, char* sequence2, int m, int n) {


int LCS[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
LCS[i][j] = 0;
else if (sequence1[i - 1] == sequence2[j - 1])
LCS[i][j] = LCS[i - 1][j - 1] + 1;
else
LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1]);
}
}

return LCS[m][n];
}

int main() {
char sequence1[] = "ABCD";
char sequence2[] = "ACDF";
int m = strlen(sequence1);
int n = strlen(sequence2);

int lcsLength = lcsLength(sequence1, sequence2, m, n);


printf("Length of the Longest Common Subsequence: %d\n", lcsLength);

return 0;
}
```
Input:ABCD and ACDF
output:3

7.Find Peak Element: Given an array of integers, find a peak element, which is an element
that is greater than or For example, in the array [1, 3, 5, 2, 6], both 5 and 6 are peak
elements

```c
#include <stdio.h>

int findPeakElement(int arr[], int size) {


int left = 0;
int right = size - 1;

while (left < right) {


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

if (arr[mid] < arr[mid + 1]) {


left = mid + 1;
} else {
right = mid;
}
}

return left;
}

int main() {
int arr[] = {1, 3, 5, 2, 6};
int size = sizeof(arr) / sizeof(arr[0]);

int peakIndex = findPeakElement(arr, size);


int peakElement = arr[peakIndex];

printf("Peak element: %d\n", peakElement);

return 0;
}

```
Input: array[]= {5, 10, 20, 15}
Output: 20
Explanation: The element 20 has neighbors 10 and 15, both of them are less than 20.

8.Word Search: Given a 2D board of letters and a word, determine if the word exists in the
grid. The word can be constructed from letters of adjacent cells (horizontally or vertically).
For example, given the board:

[ ['A', 'B', 'C', 'E'],

['s', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']

The word "ABCCED" exists in the board, but "SEE" does not

```c
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#define ROWS 3
#define COLS 4

bool isValid(int row, int col, int visited[ROWS][COLS]) {


return (row >= 0 && row < ROWS && col >= 0 && col < COLS && !visited[row][col]);
}
bool searchWord(char board[ROWS][COLS], int row, int col, char* word, int index, int
visited[ROWS][COLS]) {
if (index == strlen(word)) {
return true;
}

if (isValid(row, col, visited) && board[row][col] == word[index]) {


visited[row][col] = 1;

int rowOffset[] = { -1, 0, 1, 0 };


int colOffset[] = { 0, 1, 0, -1 };

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


if (searchWord(board, row + rowOffset[i], col + colOffset[i], word, index + 1, visited)) {
return true;
}
}

visited[row][col] = 0;
}

return false;
}

bool wordSearch(char board[ROWS][COLS], char* word) {


int visited[ROWS][COLS];
memset(visited, 0, sizeof(visited));

for (int row = 0; row < ROWS; row++) {


for (int col = 0; col < COLS; col++) {
if (searchWord(board, row, col, word, 0, visited)) {
return true;
}
}
}

return false;
}

int main() {
char board[ROWS][COLS] = {
{ 'A', 'B', 'C', 'E' },
{ 's', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' }
};

char* word1 = "ABCCED";


char* word2 = "SEE";

if (wordSearch(board, word1)) {
printf("%s exists in the board.\n", word1);
} else {
printf("%s does not exist in the board.\n", word1);
}

if (wordSearch(board, word2)) {
printf("%s exists in the board.\n", word2);
} else {
printf("%s does not exist in the board.\n", word2);
}

return 0;
}
``
Input:
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

9.Rat in a Maze: Given a 2D matrix representing a maze, find a path for a rat to reach its
destination (bottom-right corner) from the top-left corner.The rat can move in four directions:
up, down, left, and right. 0's in the matrix represent a valid path,while 1's represent
obstacles. the output should be taken by the rat

```c
#include <stdbool.h>
#include <stdio.h>

#define SIZE 4

bool isValid(int maze[SIZE][SIZE], int row, int col) {


return (row >= 0 && row < SIZE && col >= 0 && col < SIZE && maze[row][col] == 0);
}

bool solveMazeUtil(int maze[SIZE][SIZE], int row, int col, int sol[SIZE][SIZE]) {


if (row == SIZE - 1 && col == SIZE - 1) {
sol[row][col] = 1;
return true;
}

if (isValid(maze, row, col)) {


sol[row][col] = 1;

if (solveMazeUtil(maze, row + 1, col, sol))


return true;
if (solveMazeUtil(maze, row, col + 1, sol))
return true;

sol[row][col] = 0;
return false;
}

return false;
}

void solveMaze(int maze[SIZE][SIZE]) {


int sol[SIZE][SIZE] = { {0} };

if (solveMazeUtil(maze, 0, 0, sol)) {
printf("Path found:\n");
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
printf("%d ", sol[row][col]);
}
printf("\n");
}
} else {
printf("No path found.\n");
}
}

int main() {
int maze[SIZE][SIZE] = {
{ 0, 1, 0, 0 },
{ 0, 0, 0, 1 },
{ 1, 0, 0, 0 },
{ 0, 1, 1, 0 }
};

solveMaze(maze);

return 0;
}
```
Input:

{1, 0, 0, 0}
{1, 1, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 1}

Output:All entries in solution path are marked as 1

10.Count Islands: Given a 2D matrix representing a map, where 0's represent water and 1's
represent land,count the Number of islands inthe map

An island is formed by connecting adjacent lands (horizontally or vertically). Assume that the
borders of the map are all water.for example:

Input:

[1, 1, 0, 0, 0],

[1, 1, 0, 1, 1],

[0, 0, 0, 1, 1], [0, 0, 0, 0, 0],

[1, 1, 0, 0, 0]

```c
#include <stdbool.h>
#include <stdio.h>

#define ROWS 5
#define COLS 5

bool isValid(int map[ROWS][COLS], int row, int col, bool visited[ROWS][COLS]) {


return (row >= 0 && row < ROWS && col >= 0 && col < COLS && map[row][col] == 1 &&
!visited[row][col]);
}

void DFS(int map[ROWS][COLS], int row, int col, bool visited[ROWS][COLS]) {


static int rowNbr[] = { -1, 0, 0, 1 };
static int colNbr[] = { 0, -1, 1, 0 };

visited[row][col] = true;

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


if (isValid(map, row + rowNbr[k], col + colNbr[k], visited))
DFS(map, row + rowNbr[k], col + colNbr[k], visited);
}
}
int countIslands(int map[ROWS][COLS]) {
bool visited[ROWS][COLS] = { { false } };
int count = 0;

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


for (int j = 0; j < COLS; j++) {
if (map[i][j] == 1 && !visited[i][j]) {
DFS(map, i, j, visited);
count++;
}
}
}

return count;
}

int main() {
int map[ROWS][COLS] = {
{ 1, 1, 0, 0, 0 },
{ 1, 1, 0, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0 }
};

int islandCount = countIslands(map);


printf("Number of islands: %d\n", islandCount);

return 0;
}
```
Input: mat[][] = {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 0}}
Output: 4

You might also like