✅ Day 5 Solution - DSA with C

 

✅ 1. Implement your own strlen()


#include <stdio.h> int my_strlen(char str[]) { int i = 0; while (str[i] != '\0') { i++; } return i; } int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); printf("Length of string = %d\n", my_strlen(str)); return 0; }

✅ 2. Implement your own strcpy()


#include <stdio.h> void my_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; // Null-terminate } int main() { char src[100], dest[100]; printf("Enter a string to copy: "); scanf("%s", src); my_strcpy(dest, src); printf("Copied string: %s\n", dest); return 0; }

✅ 3. Implement your own strcmp()


#include <stdio.h> int my_strcmp(char str1[], char str2[]) { int i = 0; while (str1[i] != '\0' && str2[i] != '\0') { if (str1[i] != str2[i]) return str1[i] - str2[i]; i++; } return str1[i] - str2[i]; // Also handles different lengths } int main() { char str1[100], str2[100]; printf("Enter two strings:\n"); scanf("%s %s", str1, str2); int result = my_strcmp(str1, str2); if (result == 0) printf("Strings are equal.\n"); else if (result < 0) printf("First string is smaller.\n"); else printf("First string is greater.\n"); return 0; }

✅ 4. LeetCode Problem: Valid Anagram

Two strings are anagrams if they contain the same characters in any order.

✨ Custom C Solution:


#include <stdio.h> #include <string.h> int isAnagram(char s[], char t[]) { int count[26] = {0}; if (strlen(s) != strlen(t)) return 0; for (int i = 0; s[i] != '\0'; i++) { count[s[i] - 'a']++; count[t[i] - 'a']--; } for (int i = 0; i < 26; i++) { if (count[i] != 0) return 0; } return 1; } int main() { char s[100], t[100]; printf("Enter first string: "); scanf("%s", s); printf("Enter second string: "); scanf("%s", t); if (isAnagram(s, t)) printf("Valid Anagram\n"); else printf("Not an Anagram\n"); return 0; }

✅ This C code solves the Valid Anagram LeetCode problem without using libraries like sort.

Comments

Popular posts from this blog

Raster scan Vs Vector Scan

Inheritance

unit -1 Introduction of Image processing