Repository navigation
Expand file tree
/
Copy pathcoding_Q&A.js
More file actions
1240 lines (941 loc) · 32.3 KB
/
Copy pathcoding_Q&A.js
File metadata and controls
1240 lines (941 loc) · 32.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Without using BUILT-IN Methods
let s = "Hello Welcome to Javascript";
let r = "";
let w = "";
for (let i = 0; i <= s.length; i++) {
if (s[i] !== " " && i !== s.length) {
w = s[i] + w;
} else {
r += w + " ";
w = "";
}
}
r = r.trim();
console.log(r);
Convert Nested Object to Simple Object (Without Functions)
Here are several ways to convert a nested object into a simple flat object using dot notation, without using any functions:
Method 1: Simple One-Level Flattening (Manual)
```javascript
// Original nested object
const nestedObject = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
country: 'USA'
},
contact: {
email: 'john@example.com',
phone: '555-1234'
}
};
// Convert to simple object manually
const simpleObject = {
name: nestedObject.name,
age: nestedObject.age,
'address.street': nestedObject.address.street,
'address.city': nestedObject.address.city,
'address.country': nestedObject.address.country,
'contact.email': nestedObject.contact.email,
'contact.phone': nestedObject.contact.phone
};
console.log(simpleObject);
```
Method 2: Using Object Spread Operator
```javascript
const nestedObject = {
user: {
personal: {
firstName: 'Alice',
lastName: 'Smith',
age: 25
},
preferences: {
theme: 'dark',
language: 'en'
}
},
settings: {
notifications: true,
privacy: 'public'
}
};
// Flatten using spread operator
const simpleObject = {
...nestedObject.user.personal,
'preferences.theme': nestedObject.user.preferences.theme,
'preferences.language': nestedObject.user.preferences.language,
'settings.notifications': nestedObject.settings.notifications,
'settings.privacy': nestedObject.settings.privacy
};
console.log(simpleObject);
```
Method 3: For Complex Objects (Manual Assignment)
```javascript
const complexObject = {
data: {
users: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
],
metadata: {
count: 2,
timestamp: '2023-12-07'
}
},
status: 'success',
code: 200
};
// Manual conversion
const flatObject = {
status: complexObject.status,
code: complexObject.code,
'data.metadata.count': complexObject.data.metadata.count,
'data.metadata.timestamp': complexObject.data.metadata.timestamp,
'data.users': complexObject.data.users // arrays are kept as-is
};
console.log(flatObject);
```
Method 4: Using Object Destructuring
```javascript
const product = {
id: 101,
details: {
name: 'Laptop',
specifications: {
processor: 'Intel i7',
ram: '16GB',
storage: '512GB SSD'
},
price: 999.99
},
inStock: true
};
// Destructure and create flat object
const { id, inStock } = product;
const { name, price } = product.details;
const { processor, ram, storage } = product.details.specifications;
const flatProduct = {
id,
inStock,
'details.name': name,
'details.price': price,
'details.specifications.processor': processor,
'details.specifications.ram': ram,
'details.specifications.storage': storage
};
console.log(flatProduct);
```
Method 5: For Multiple Similar Objects
```javascript
// Array of nested objects
const users = [
{
id: 1,
info: {
name: 'John Doe',
contact: {
email: 'john@email.com',
phone: '123-456-7890'
}
}
},
{
id: 2,
info: {
name: 'Jane Smith',
contact: {
email: 'jane@email.com',
phone: '098-765-4321'
}
}
}
];
// Convert each object manually
const flatUsers = [
{
id: users[0].id,
'info.name': users[0].info.name,
'info.contact.email': users[0].info.contact.email,
'info.contact.phone': users[0].info.contact.phone
},
{
id: users[1].id,
'info.name': users[1].info.name,
'info.contact.email': users[1].info.contact.email,
'info.contact.phone': users[1].info.contact.phone
}
];
console.log(flatUsers);
```
Method 6: Using Object.assign()
```javascript
const company = {
name: 'Tech Corp',
headquarters: {
address: '456 Tech Ave',
city: 'San Francisco',
country: 'USA'
},
employees: 500,
founded: 2010
};
// Using Object.assign()
const flatCompany = Object.assign(
{},
{
name: company.name,
employees: company.employees,
founded: company.founded
},
{
'headquarters.address': company.headquarters.address,
'headquarters.city': company.headquarters.city,
'headquarters.country': company.headquarters.country
}
);
console.log(flatCompany);
```
Sample Output:
All methods will produce similar output formats:
```javascript
// For the first example:
{
name: 'John',
age: 30,
'address.street': '123 Main St',
'address.city': 'New York',
'address.country': 'USA',
'contact.email': 'john@example.com',
'contact.phone': '555-1234'
}
```
Key Points:
1. Manual Approach: You explicitly map each nested property to a flat key
2. Dot Notation: Use quotes for keys containing dots (e.g., 'address.street')
3. Arrays: Can be kept as-is or handled differently based on needs
4. No Functions: These methods don't use any custom functions or recursion
5. Explicit: You have full control over the structure of the output
Choose the method that best fits your specific object structure and requirements!
const numbers = [1,2,3,4,5,6,7,8,9,10];
const evenNumbers = [];
for(let i = 0; i < numbers.length; i++) {
if(numbers[i] % 2 === 0) {
evenNumbers.push(numbers[i]);
}
}
console.log('Even numbers:', evenNumbers);
function filterArray(array, callback) {
// console.log(callback);
const result = [];
for(let i = 0; i < array.length; i++) {
if(callback(array[i], i, array)) {
result.push(array[i]);
}
}
// console.log(result);
return result;
}
const numbers = [1,2,3,4,5,6,7,8,9,10];
const evenNumbers = filterArray(numbers,function(num) {
return num % 2 === 0;
});
console.log('Even numbers:', evenNumbers);
function printNumbers() {
for(let i=1; i<=10; i++) {
// (function(index){
setTimeout(function() {
console.log(i);
console.log(i * 1000);
}, i * 1000);
// })(i);
}
}
printNumbers();
Of course. Here is the JavaScript code to solve the "Merge Intervals" problem shown in your image.
The core idea is to first **sort** the intervals by their starting points. Then, you iterate through the sorted intervals, merging the current interval with the previous one if they overlap.
```javascript
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
function mergeIntervals(intervals) {
// 1. Handle edge cases: if there are 0 or 1 intervals, no merging is needed.
if (intervals.length <= 1) {
return intervals;
}
// 2. Sort the intervals based on their starting value (the first number in each pair).
intervals.sort((a, b) => a[0] - b[0]);
// 3. Initialize a result array with the first interval.
const result = [intervals[0]];
// 4. Iterate through the rest of the intervals.
for (let i = 1; i < intervals.length; i++) {
const currentInterval = intervals[i];
const lastMergedInterval = result[result.length - 1];
// 5. Check for an overlap.
// An overlap occurs if the start of the current interval is less than or equal to the end of the last merged interval.
if (currentInterval[0] <= lastMergedInterval[1]) {
// If they overlap, merge them by updating the end of the last merged interval.
// The new end is the maximum of the two interval ends.
lastMergedInterval[1] = Math.max(lastMergedInterval[1], currentInterval[1]);
} else {
// If there's no overlap, add the current interval to the result array.
result.push(currentInterval);
}
}
return result;
}
// --- How to use it with your example ---
const input = [[1, 3], [5, 8], [7, 10], [15, 20]];
const output = mergeIntervals(input);
console.log("Input:", JSON.stringify(input));
console.log("Output:", JSON.stringify(output));
// Expected Output: [[1,3],[5,10],[15,20]]
```
-----
### \#\# How the Code Works ⚙️
1. **Sort:** The function first sorts the array of intervals based on their **start time**. This is the most critical step because it ensures that we can process intervals in an orderly fashion.
* `[ [1,3], [5,8], [7,10], [15,20] ]` (Your input is already sorted).
2. **Initialize:** It creates a `result` array and starts by adding the very first interval `[1,3]` to it.
3. **Iterate and Compare:** The code then loops through the remaining intervals. In each step, it compares the **current interval** with the **last interval** that was added to the `result` array.
* **Iteration 1:**
* **Current Interval:** `[5,8]`
* **Last in Result:** `[1,3]`
* **Overlap Check:** Does `5` (start of current) \<= `3` (end of last)? **No.**
* **Action:** No overlap, so `[5,8]` is added to the `result`. `result` is now `[ [1,3], [5,8] ]`.
* **Iteration 2:**
* **Current Interval:** `[7,10]`
* **Last in Result:** `[5,8]`
* **Overlap Check:** Does `7` \<= `8`? **Yes.**
* **Action:** There is an overlap\! The end of the last interval in `result` (`[5,8]`) is updated to be the maximum of `8` and `10`. `result` becomes `[ [1,3], [5,10] ]`.
* **Iteration 3:**
* **Current Interval:** `[15,20]`
* **Last in Result:** `[5,10]`
* **Overlap Check:** Does `15` \<= `10`? **No.**
* **Action:** No overlap, so `[15,20]` is added to the `result`. `result` is now `[ [1,3], [5,10], [15,20] ]`.
4. **Return:** After the loop finishes, the `result` array contains all the merged intervals.
const arr = [5, 2, 9, 1, 5, 6];
// Descending Bubble Sort without using array methods
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
// Swap elements
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
console.log("Descending Order:", arr);
To complete your code so that it **finds and logs the duplicates along with their counts** from a string (`str`), you need to:
1. Track the **frequency of each character**.
2. Identify **duplicates** (those with count > 1).
3. Log them with their **counts**.
Here’s the **corrected and completed code**:
const str = "programming"; // Example input
const arr = []; // To store unique characters
const freq = {}; // To store frequency of characters
for (let i = 0; i < str.length; i++) {
const char = str[i];
// Count frequency
freq[char] = (freq[char] || 0) + 1;
// Store unique characters
if (!arr.includes(char)) {
arr.push(char);
}
}
console.log("Length of unique array:", arr.length);
// Find and log duplicates with counts
console.log("Duplicates and their counts:");
for (const char in freq) {
if (freq[char] > 1) {
console.log(`${char}: ${freq[char]}`);
}
}
```
### 🔍 Example Output for `str = "programming"`:
```
Length of unique array: 8
Duplicates and their counts:
r: 2
g: 2
m: 2
const arr = [];
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (!arr.includes(char)) { // Check for duplicates
arr.push(char);
}
}
console.log("Length of unique array:", arr.length);
// Example usage:
const myString = "hello";
const uniqueArray = stringToUniqueArray(myString);
console.log(uniqueArray); // Output: ["h", "e", "l", "o"] and console logs 4
const myString2 = "aabbccddeeff";
const uniqueArray2 = stringToUniqueArray(myString2);
console.log(uniqueArray2); // Output: ["a", "b", "c", "d", "e", "f"] and console logs 6
const myString3 = "";
const uniqueArray3 = stringToUniqueArray(myString3);
console.log(uniqueArray3); // output: [] and console logs 0
const notString = 123;
const notStringArray = stringToUniqueArray(notString);
console.log(notStringArray); // output: "Input is not a string"
const inputString = "Abcdedfavafdalafad";
const outputString = processString(inputString);
console.log(outputString); // Abcde, dfav, afd, al, af, ad
function processString(str) {
const result = [];
let current = "";
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (current.includes(char)) {
result.push(current);
current = char; // start new group
} else {
current += char;
}
}
if (current) {
result.push(current);
}
return result.join(", ");
}
const inputString = "Abcdedfavafdalafad";
const outputString = processString(inputString);
console.log(outputString); // Abcde, dfav, afd, al, af, ad
Or
========≠===≠==================≠==≠==========≠{=============
const inputString = "Abcdefavafdalfad";
function processString(str) {
let parts = [];
let partLengths = [5, 4, 3, 2, 2, 2];
let startIndex = 0;
for (let length of partLengths) {
let part = str.substring(startIndex, startIndex + length);
parts.push(part);
startIndex += length;
}
return parts.join(", ");
}
const outputString = processString(inputString);
console.log(outputString); // "Abcde, dfav, afd, al, af, ad"
Write a function that accepts an integer as parameter and prints this pattern.
In this case the input parameter is number 5
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
function printPattern(n) {
// Outer loop to handle the number of rows
for (let i = 0; i < n; i++) {
let row = '';
// Inner loop to handle the numbers in each row
for (let j = n; j > i; j--) {
row += j + ' ';
}
console.log(row.trim());
}
}
// Call the function with the input parameter 5
printPattern(5);
Reverse Words in a String: Write a function that takes a sentence as input and returns the sentence with the words reversed.
For example, if the input is "Hello, World!", the output should be "World! Hello,".
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
Second Largest Number: Develop a function that finds the second largest number in an array of numbers.
For example, if the input is [3, 8, 2, 10, 5], the output should be 8.
function findSecondLargestNumber(arr) {
let firstLargest = arr[0];
let secondLargest = arr[1];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > firstLargest) {
secondLargest = firstLargest;
firstLargest = arr[i];
} else if (arr[i] > secondLargest && arr[i] !== firstLargest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
const result= findSecondLargestNumber([3, 8, 2, 10, 5]);
console.log(result);
another ways:
function findSecondLargest(arr) {
if (arr.length < 2) {
throw new Error("Array must contain at least two elements");
}
let largest = -Infinity;
let secondLargest = -Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] !== largest) {
secondLargest = arr[i];
}
}
if (secondLargest === -Infinity) {
throw new Error("No second largest element found");
}
return secondLargest;
}
// Example usage:
const numbers = [3, 8, 2, 10, 5];
console.log(findSecondLargest(numbers)); // Output: 8
// FIRST LARGEST NUMBER
function findLargestNumber(arr) {
let largest = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
Check for Palindrome: Write a function that takes a string as input and checks if it is a palindrome.
A palindrome is a word or phrase that reads the same forwards and backward. For example, if the input is "level", the output should be true.
function isPalindrome(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return str === reversed;
}
const result= isPalindrome("level");
console.log(result);
FizzBuzz: Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and
for the multiples of five, print "Buzz". For numbers that are multiples of both three and five, print "FizzBuzz".
for (let i = 1; i <= 100; i++) {
let output = '';
if (i % 3 === 0) {
output += 'Fizz';
}
if (i % 5 === 0) {
output += 'Buzz';
}
console.log(output || i);
}
Find the missing number: Given an array of numbers from 1 to N, where one number is missing,
write a function to find the missing number. For example, if the input is [1, 2, 4, 5, 6], the output should be 3.
function findMissingNumber(arr) {
const n = arr.length + 1; // since one number is missing, the length of the full array should be arr.length + 1
const expectedSum = (n * (n + 1)) / 2; // sum of numbers from 1 to N
let actualSum = 0;
for (let i = 0; i < arr.length; i++) {
actualSum += arr[i];
}
return expectedSum - actualSum;
}
// Example usage:
const numbers = [1, 2, 4, 5, 6];
console.log(findMissingNumber(numbers)); // Output: 3
find and log the duplicates along with their counts in an array,
function findDuplicates(arr) {
var counts = {};
var duplicates = {};
// Count occurrences of each element
for (var i = 0; i < arr.length; i++) {
var num = arr[i];
if (counts[num] === undefined) {
counts[num] = 1;
} else {
counts[num]++;
}
}
// Identify duplicates
for (const element in counts) {
if (counts[element] > 1) {
duplicates[element] = counts[element];
}
}
// Log duplicates and their counts
console.log('Duplicates and their counts:', duplicates);
}
// Example usage:
var arr = [1, 2, 2, 3, 4, 4, 5];
findDuplicates(arr);
Remove duplicates from an array: Write a function that takes an array as input and returns a new array with duplicate elements removed.
For example, if the input is [1, 2, 2, 3, 4, 4, 5], the output should be [1, 2, 3, 4, 5].
function removeDuplicates(arr) {
const uniqueArray = [];
for (let i = 0; i < arr.length; i++) {
let isUnique = true;
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
isUnique = false;
break; // Exit inner loop if duplicate found
}
}
if (isUnique) {
uniqueArray.push(arr[i]);
}
}
return uniqueArray;
}
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = removeDuplicates(arr);
console.log(uniqueArray);
Check for Anagrams: Write a function that takes two strings as input and checks if they are anagrams.
Anagrams are two words or phrases that use the same letters in a different order. For example, if the inputs are "listen" and "silent", the output should be true.
function areAnagrams(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const charCount1 = {};
const charCount2 = {};
// Count characters in str1
for (let i = 0; i < str1.length; i++) {
const char = str1[i];
charCount1[char] = (charCount1[char] || 0) + 1;
}
// Count characters in str2
for (let i = 0; i < str2.length; i++) {
const char = str2[i];
charCount2[char] = (charCount2[char] || 0) + 1;
}
// Compare character counts
for (let char in charCount1) {
if (charCount1[char] !== charCount2[char]) {
return false;
}
}
return true;
}
// Example usage:
const str1 = "listen";
const str2 = "silent";
console.log(areAnagrams(str1, str2)); // Output: true
const str3 = "hello";
const str4 = "world";
console.log(areAnagrams(str3, str4)); // Output: false
Find the longest word: Write a function that takes a sentence as input and returns the longest word in the sentence.
For example, if the input is "The quick brown fox jumps over the lazy dog", the output should be "jumps".
function findLongestWord(sentence) {
// Split the sentence into words
const words = sentence.split(" ");
// Initialize variables
let longestWord = "";
let longestWordLength = 0;
// Loop through each word
for (let i = 0; i < words.length; i++) {
const currentWord = words[i];
const currentWordLength = currentWord.length;
// Check if current word is longer than the current longest
if (currentWordLength > longestWordLength) {
longestWord = currentWord;
longestWordLength = currentWordLength;
}
}
// Return the longest word
return longestWord;
}
// Example usage
const sentence = "The quick brown fox jumps over the lazy dog";
const longestWord = findLongestWord(sentence);
console.log(longestWord); // Output: "jumps"
function isPrime(num) {
if (num <= 1) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function countCharacterOccurrences(str, char) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
count++;
}
}
return count;
}
JavaScript function to find and log duplicate words in a sentence:
function findDuplicateWords(sentence) {
// Convert the sentence to lowercase and split it into words
const words = sentence.toLowerCase().split(/\W+/);
const wordCount = {};
const duplicates = [];
// Count the occurrences of each word
words.forEach(word => {
if (word) {
if (wordCount[word]) {
wordCount[word]++;
} else {
wordCount[word] = 1;
}
}
});
// Identify the duplicate words
for (const word in wordCount) {
if (wordCount[word] > 1) {
duplicates.push(word);
}
}
// Log the duplicate words
console.log("Duplicate words:", duplicates);
}
// Example usage
const sentence = "This is a test. This test is only a test.";
findDuplicateWords(sentence);
reverse the words in a sentence without using array methods,
function reverseWords(sentence) {
let result = '';
let word = '';
for (let i = sentence.length - 1; i >= 0; i--) {
if (sentence[i] === ' ') {
if (word !== '') {
result = word + ' ' + result;
word = '';
}
} else {
word = sentence[i] + word;
}
}
if (word !== '') {
result = word + ' ' + result;
}
// Remove the trailing space
return result.trim();
}
// Example usage
const sentence = "This is a test sentence.";
const reversedSentence = reverseWords(sentence);
console.log(reversedSentence); // Output: "sentence. test a is This"
reverse the words in a sentence without using array methods, and position of special characters must not change
function reverseWordsPreserveSpecial(sentence) {
let result = '';
let word = '';
let specialChars = {};
// Collect special characters and their positions
for (let i = 0; i < sentence.length; i++) {
if (!(/[a-zA-Z]/).test(sentence[i])) {
specialChars[i] = sentence[i];
}
}
// Reverse the words in the sentence
for (let i = sentence.length - 1; i >= 0; i--) {
if ((/[a-zA-Z]/).test(sentence[i])) {
word = sentence[i] + word;
} else if (sentence[i] === ' ') {
if (word !== '') {
result += word + ' ';
word = '';
}
}
}
// Add the last word
if (word !== '') {
result += word;
}
// Insert special characters back in their original positions
let finalResult = '';
let resultIndex = 0;
for (let i = 0; i < sentence.length; i++) {
if (specialChars.hasOwnProperty(i)) {
finalResult += specialChars[i];
} else {
finalResult += result[resultIndex] || '';
resultIndex++;
}
}
return finalResult;
}
// Example usage
const sentence = "Th!s is, a t3st s*ntence.";
const reversedSentence = reverseWordsPreserveSpecial(sentence);